我是Perl编程的新手,并且试图在Perl子例程中传递单个参数并在子例程中修改它。问题是,在子例程中,变量仍保留其原始值。只有在返回并退出子程序时,它才会反映其新的/更改的值。
@arr1 = qw(166 2 3 4);
$a, $b, $c, $d;
($a, $b, $c, $d) = @arr1;
$mnop = &oneparam("$a");
print "mnop returned from oneparam is :", $mnop, "\n";
sub oneparam{
$qrst = shift;
print "param passed is ", $qrst, "\n";
$qsrt = 166 + 1;
print "qrst inside method ", $qrst, "\n";
return $qsrt;
}
print "qsrt outside method, ", $qsrt, "\n";
它提供以下o / p:
param passed is 166
**qrst inside method 166**
mnop returned from oneparam is :167
qsrt outside method, 167
粗体(qrst ... 166)的行应该是167.有人可以帮我理解为什么它的166?
答案 0 :(得分:3)
您没有限制任何变量的范围。您应该使用my
声明变量以限制其范围。
始终使用use strict; use warnings;
。当你忘记声明一个变量时,这会导致错误。
use strict;
use warnings;
sub oneparam {
my $qrst = shift;
$qsrt = $qrst + 1;
return $qsrt;
}
for my $n (qw(166 2 3 4)) {
my $mnop = oneparam($n);
print "oneparam($a) = $mnop\n";
}