相关疑难解决方法(0)

Perl中foreach循环的默认范围是什么?

在Perl中,在foreach循环中使用'my'会产生什么影响吗?无论是否使用'my',索引变量似乎始终是本地的.那么你可以在foreach循环中删除'my'并且仍然在循环体内有私有范围吗?

可以看出,使用'for'循环使用/不使用'my'之间存在差异:

use strict; 
use warnings; 

my ($x, $y) = ('INIT', 'INIT'); 

my $temp = 0; 

for ($x = 1; $x < 10; $x++) {
 $temp = $x+1; 
}

print "This is x: $x\n";   # prints 'This is x: 10'. 

for (my $y = 1; $y < 10; $y++) {
 $temp = $y+1; 
}

print "This is y: $y\n";   # prints 'This is y: INIT'. 
Run Code Online (Sandbox Code Playgroud)

但是在foreach上它似乎没有效果:

my ($i, $j) = ('INIT', 'INIT'); 

foreach $i (1..10){
    $temp = $i+1;
}

print …
Run Code Online (Sandbox Code Playgroud)

perl foreach scope

16
推荐指数
3
解决办法
3665
查看次数

当我重新声明Perl foreach控制变量时,为什么不收到警告?

为什么$i在以下代码中没有重新声明的警告?

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

for my $i (1..3) {
  my $i = 'DUMMY';
  print Dumper $i;
}
Run Code Online (Sandbox Code Playgroud)

variables perl warnings

10
推荐指数
2
解决办法
414
查看次数

对于Loop和Lexically Scoped变量

版本#1

use warnings;
use strict;

my $count = 4;

for $count (1..8) {
    print "Count = $count\n";
    last if ($count == 6);
}

if (not defined($count)) {
    print "Count not defined\n";
}
else {
    print "Count = $count\n";
}
Run Code Online (Sandbox Code Playgroud)

这打印:

1
2
3
4
5
6
4
Run Code Online (Sandbox Code Playgroud)

为什么?因为for循环$count在其块内创建了自己的词法范围版本.

版本#2

use warnings;
use strict;

my $count;
for $count (1..8) {
    print "Count = $count\n";
    last if ($count == 6);
}

if (not defined($count)) {
    print "Count not …
Run Code Online (Sandbox Code Playgroud)

perl

4
推荐指数
2
解决办法
2887
查看次数

标签 统计

perl ×3

foreach ×1

scope ×1

variables ×1

warnings ×1