tags:

views:

178

answers:

2

Hello friends,

I have encountered a difficulty in understanding the subroutine syntax.

using the following code:

sub build_dyne_file{
open(DYNAP, "+>$veri_dir/$dyna_para") or die $!;
    for (keys %hash){
     print DYNAP "#define ",$_," ",$hash{$_}->[$i],"\n";
    }
    close(DYNAP);
}

for (my $i = 0 ; $i <$TEST_QUOTA ; $i++){
    build_dyna_file($i);
}

In the 'build dyne file' subroutine, the 'for loop' iterates over the hash keys, while the $i parameter used inside the external 'for loop'.

I hope you understand the problem, If not - I'll try to explain it more properly.

thanks for any answer.

+1  A: 

You need to get the $i parameter in your subroutine:

sub build_dyne_file
{
  open(DYNAP, "+>$veri_dir/$dyna_para") or die $!;

  # the crucial omission...
  my $i = shift;

    for (keys %hash){
        print DYNAP "#define ",$_," ",$hash{$_}->[$i],"\n";
    }
    close(DYNAP);
}
1800 INFORMATION
This might be a matter of preference, but I very much prefer to shift the arguments first in a subroutine (in this case before, not after, opening the file).
Anon
+6  A: 

You have to receive the parameter.

sub build_dyne_file { 
    my $i = shift; # take it off the parameter queue
    ...

You declared it with a lexical scope in the lower for loop ( using my ), so therefore only that loop can "see" it. When you pass it to build_dyne_file, you need to receive the parameter.

Please see perlsub

Axeman
Thanks!As I thought - PERL is that simple...
YoDar
That's "perl", not "PERL". It's not an acronym.
Ether
Actually, when referring to the language, please use "Perl".
Inshallah