此代码运行并产生输出abc:
for(10..12){$_=sprintf"%x",$_;print}
Modification of a read-only value attempted at ...但是此代码因错误而死:
for(10,11,12){$_=sprintf"%x",$_;print}
为什么这些结构的处理方式不同?
(此代码也有效:)
for(10..10,11..11,12..12){$_=sprintf"%x",$_;print}
此代码运行并产生输出abc:
for(10..12){$_=sprintf"%x",$_;print}
Modification of a read-only value attempted at ...但是此代码因错误而死:
for(10,11,12){$_=sprintf"%x",$_;print}
为什么这些结构的处理方式不同?
(此代码也有效:)
for(10..10,11..11,12..12){$_=sprintf"%x",$_;print}
可能是因为当你foreach超过一个范围时会出现“计数循环”优化。for (1, 2, 3, 4)实际上构造了列表 (1, 2, 3, 4),其中包含那些特定的只读值,但for (1..4)没有;它只是从范围的开始迭代到结束,依次给出$_每个连续的值,我猜没有人认为当你尝试分配给它时匹配行为是值得的$_。
您的最后一个片段正在做不应该做的事情。最好使用以下代码进行演示:
for (1..2) {
for (1..3, 5..7) {
print $_++;
}
print "\n";
}
输出:
123567
234678
就我而言,有三种 for 循环:
for (my $i=1; $i<4; ++$i))for my $i (1,2,3))for my $i (1..3))