作者:叶晴琼 | 来源:互联网 | 2023-01-28 16:02
是否可以++
在字符串插值中使用运算符?我尝试过以下方法:
my $i = 0;
foreach my $line (@lines) {
print "${i++}. $line\n";
}
但我明白了 Compile error: Can't modify constant item in postincrement (++)
1> ikegami..:
Bareword i
相当于"i"
,所以你在做"i"++
.
你要:
print($i++, ". $line\n");
更简单:
print("$i. $line\n");
++$i;
将值嵌入字符串的好方法是sprintf
/ printf
.
printf("%d. %s\n", $i++, $line);
请注意,use strict
不允许使用裸字,因此您也可以获得
Bareword "i" not allowed while "strict subs" in use
在您提到的错误之后,这个错误很奇怪.