) { if (/ad-6ren">
gpt4 book ai didi

perl - Perl 脚本错误; "Uninitialized Value"?;

转载 作者:行者123 更新时间:2023-12-04 05:54:32 24 4
gpt4 key购买 nike

我有以下脚本:

use 5.12.4;
use strict;
use warnings;

say "Enter a functionality:";
while (<>) {
if (/add/) {
say "Enter your numbers:";
my @a = (<>);
my $sum += $_ for @a;
say $sum;
}
}

当我运行这个程序时,它提示:

Enter a functionality:



我输入 add它说:
Enter your numbers:

我在不同的输入行上输入了几个数字,后面跟着 [ctrl]Z并得到以下错误:
Use of uninitialized value $sum in say at C:\myperl\Math-Master\math-master.pl l
ine 11, <> line 9.

为什么我的代码没有添加所有输入?为什么会出现这个错误?

最佳答案

不能在声明语句上使用 postscript 循环。变量 $sum应该在每个循环中递增,它不能在声明的同一语句中。您必须首先声明它,然后使用 postscript 循环分配给它:

my $sum;
$sum += $_ for @a;

您可以考虑使用 List::Util为此,并跳过临时变量 @a .并移动 say在while循环内:
use List::Util qw(sum);

say "Enter a functionality:";
while (<>) {
if (/add/) {
say "Enter your numbers:";
say "Sum: ", sum(<>);
}
say "Enter a functionality:";
}

但这有点笨拙。为什么不:
while (<>) {
if (/add/) {
say "Enter your numbers, separated by space: ";
say "Sum: ", sum(split " ", <>);
}
}

这样,您不必按 ctrl-Z (ctrl-D) 来停止输入。

关于perl - Perl 脚本错误; "Uninitialized Value"?;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9675905/

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