相关疑难解决方法(0)

for循环不会修改`my`变量,但会修改`my`变量

在Perl 5.20中,for循环似乎能够修改模块范围的变量,但不能修改父范围中的词法变量.

#!/usr/bin/env perl
use strict;
use warnings;

our $x;

sub print_func {
    print "$x\n";
}

for $x (1 .. 10) {
    print_func; 
}
Run Code Online (Sandbox Code Playgroud)

像您期望的那样打印1到10,但以下不是:

#!/usr/bin/env perl
use strict;
use warnings;

my $x;

sub print_func {
    print "$x\n";
}

for $x (1 .. 10) {
    print_func; 
}
Run Code Online (Sandbox Code Playgroud)

发出以下警告10次:

Use of uninitialized value $x in concatenation (.) or string at perl-scoping.pl line 8.
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?我知道perl子例程不能嵌套(并且始终具有模块范围),因此它们无法关闭my变量似乎是合乎逻辑的.在这种情况下,perl in strictmode应该使用如下消息拒绝第二个程序:

Global symbol "$x" requires explicit package name at perl-scoping.pl line 6.
Global …
Run Code Online (Sandbox Code Playgroud)

perl

13
推荐指数
1
解决办法
200
查看次数

在"foreach"循环中发生了什么样的本地化?

来自perldoc perlsyn关于Foreach循环的主题:

如果先前使用my声明了变量,它将使用该变量而不是全局变量,但它仍然本地化为循环.

但请考虑这个例子:

use Devel::Peek;
my $x = 1;
Dump $x;
for $x ( 1 ) { Dump $x }

SV = IV(0x8117990) at 0x8100bd4
  REFCNT = 1
  FLAGS = (PADBUSY,PADMY,IOK,pIOK)
  IV = 1
SV = IV(0x8117988) at 0x8100bf8
  REFCNT = 2
  FLAGS = (IOK,READONLY,pIOK)
  IV = 1
Run Code Online (Sandbox Code Playgroud)

看起来这些变量并不相同.这是文档中的错误,还是我错过了什么?

perl scope localization

4
推荐指数
1
解决办法
272
查看次数

标签 统计

perl ×2

localization ×1

scope ×1