我对我的小perl脚本感到困惑。 我已经将两个值传递给了例程,但是,只有第一个在子路径中工作。
#!usr/bin/perl
sub even_number_printer_gen {
my ( $input1, $input2 ) = @_;
#my $input1=shift;
#my $input2=shift;
print
"after shifting, the input1 is $input1 and the input2 is $input2\n";
if ( $input1 % 2 ) { $input1++ }
if ( $input2 % 2 ) { $input2++ }
$rs = sub { #subroutin 1, everytime add 2 in $input1
print "$input1 ";
$input1 += 2;
};
$rs2 = sub { #subroutin 2, everytime add 3 in $input2
print "$input2 ";
$ipnut2 += 3;
};
@rs3 = ( $rs, $rs2 );
return @rs3; #return two subroutins as an array
}
@iterator = &even_number_printer_gen( 31, 20 );
for ( $i = 0; $i < 10; $i++ ) {
&{ $iterator[0] }; #refer subroutin 1
&{ $iterator[1] }; #refer subroutin 2
print "\n";
}
print "done!\n";
输出
after shifting, the input1 is 31 and the input2 is 20
32 20
34 20
36 20
38 20
40 20
42 20
44 20
46 20
48 20
50 20
done!
为什么第二个值不会改变?
答案 0 :(得分:2)
您写道:
$ipnut2 += 3;
应该是:
$input2 += 3;
在我的电脑上
f.jardon@xxxxx 11:49:04 ~/tmp
$ cat fixedperl.pl
#!/usr/bin/perl
sub even_number_printer_gen {
my ( $input1, $input2 ) = @_;
#my $input1=shift;
#my $input2=shift;
print
"after shifting, the input1 is $input1 and the input2 is $input2\n";
if ( $input1 % 2 ) { $input1++ }
if ( $input2 % 2 ) { $input2++ }
$rs = sub { #subroutin 1, everytime add 2 in $input1
print "$input1 ";
$input1 += 2;
};
$rs2 = sub { #subroutin 2, everytime add 3 in $input2
print "$input2 ";
$input2 += 3; ## <<<<====================== HERE IS THE FIX
};
@rs3 = ( $rs, $rs2 );
return @rs3; #return two subroutins as an array
}
@iterator = &even_number_printer_gen( 31, 20 );
for ( $i = 0; $i < 10; $i++ ) {
&{ $iterator[0] }; #refer subroutin 1
&{ $iterator[1] }; #refer subroutin 2
print "\n";
}
print "done!\n";
f.jardon@xxxxx 11:49:06 ~/tmp
$ ./fixedperl.pl
after shifting, the input1 is 31 and the input2 is 20
32 20
34 23
36 26
38 29
40 32
42 35
44 38
46 41
48 44
50 47
done!