gpt4 book ai didi

perl - 有没有办法修改 foreach 循环变量?

转载 作者:行者123 更新时间:2023-12-03 18:17:00 24 4
gpt4 key购买 nike

以下代码给出了错误消息:

#!/usr/bin/perl -w

foreach my $var (0, 1, 2){
$var += 2;
print "$var\n";
}
Modification of a read-only value attempted at test.pl line 4.
有什么办法可以修改 $var ? (我只是出于好奇而问;实际上,看到此错误消息我感到非常惊讶。)

最佳答案

foreach $var (@list)构造, $var$var 的内存地址的意义上说,成为循环元素的别名。将与 @list 的元素具有相同的地址.因此,您的示例代码尝试修改只读值,您会收到错误消息。

这个小脚本将演示 foreach 中发生的事情构造:

my @a = (0,1,2);
print "Before: @a\n";
foreach my $var (@a) {
$var += 2;
}
print "After: @a\n";

Before: 0 1 2
After: 2 3 4

附加信息: This item来自 perlsyn 很容易掩盖,但给出了整个勺子:

Foreach loops

...

If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the "foreach" loop index variable is an implicit alias for each item in the list that you're looping over.

关于perl - 有没有办法修改 foreach 循环变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1485453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com