我期待@arr1
' 的最后一个元素作为此代码的输出:
#!/usr/bin/perl
my @arr1 = qw(son kon bon won kon don pon won pon don won);
my $innr_element = '';
foreach $innr_element ( @arr1 ) {
## do something
}
print "--->$innr_element<---\n";
但我什么也没得到(空白输出)。如果$innr_element
由 Perl 在内部创建为块范围变量(内部到 foreach),那么下面应该可以正常工作。
#!/usr/bin/perl
use strict;
my @arr1 = qw(son kon bon won kon don pon won pon don won);
#my $innr_element = '';
foreach $innr_element ( @arr1 ) {
##do something
}
print "--->$innr_element<---\n";
但上面的代码返回下面的错误。
Global symbol "$innr_element" requires explicit package name at test.pl line 5.
Global symbol "$innr_element" requires explicit package name at test.pl line 8.
Execution of test.pl aborted due to compilation errors.
所以很明显 Perl 没有隐式地创建内部变量。
这份文件也是这么说的。If you declare VAR with my, the scope of the variable will extend throughout the foreach statement, but not beyond it.
这是另一个 perl 魔法还是我错过了什么?