Perl脚本错误&引用;未初始化值“?”;?;
我有以下脚本:Perl脚本错误&引用;未初始化值“?”;?;,perl,Perl,我有以下脚本: 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; } } 我在单独的输入行中输入了几个数字,
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;
}
}
我在单独的输入行中输入了几个数字,后跟[ctrl]Z
,得到以下错误:
Use of uninitialized value $sum in say at C:\myperl\Math-Master\math-master.pl l
ine 11, <> line 9.
在C:\myperl\Math Master\Math-Master.pl中使用未初始化值$sum
第11行,第9行。
为什么我的代码不添加所有输入?为什么会出现此错误?不能在声明语句上使用postscript循环。变量
$sum
应该在每个循环中递增,它不能在声明的同一语句中。必须首先声明它,然后使用postscript循环分配给它:
my $sum;
$sum += $_ for @a;
您可以考虑使用此方法,跳过临时变量<代码> @ A<代码>。并在while循环内移动
say
:
use List::Util qw(sum);
say "Enter a functionality:";
while (<>) {
if (/add/) {
say "Enter your numbers:";
say "Sum: ", sum(<>);
}
say "Enter a functionality:";
}
use List::Util qw(sum);
说“输入功能:”;
而(){
如果(/add/){
说“输入你的号码:”;
说“Sum:”,Sum();
}
说“输入功能:”;
}
但这有点笨重。为什么不:
while (<>) {
if (/add/) {
say "Enter your numbers, separated by space: ";
say "Sum: ", sum(split " ", <>);
}
}
while(){
如果(/add/){
说“输入您的数字,用空格分隔:”;
说“和:”,和(分开“);
}
}
这样,你不必按下CTRL Z(CTRL—D)来停止输入。
除了TLPS回答之外,你可以考虑使用这样的东西:
chomp(my @a = (<>));
这里有一种方法;比较和学习:
use 5.012; # implies 'use strict'
use warnings;
say "Enter a functionality:";
while (<>) {
if (/add/) {
say "Enter your numbers:";
my @nums;
while (1) {
my $in = <>; # read one line
last unless $in =~ m/^\d+$/; # only numbers
push @nums, $in;
}
next unless @nums;
my $sum;
$sum += $_ for @nums;
say $sum;
}
}
使用5.012;#暗示“严格使用”
使用警告;
说“输入功能:”;
而(){
如果(/add/){
说“输入你的号码:”;
我的@nums;
而(1){
我的$in=#读一行
最后,除非$in=~m/^\d+$/;#仅限数字
按@nums$in;
}
下一步除非@nums;
我的$sum;
$sum+=$表示@nums;
比如说$sum;
}
}
能否更新标题,使其反映实际问题?(提示:在失败的情况下,@a的$\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
use List::Util qw/sum/;
chomp(my @a = (<>));
my $sum = sum @a;
say $sum;
use 5.012; # implies 'use strict'
use warnings;
say "Enter a functionality:";
while (<>) {
if (/add/) {
say "Enter your numbers:";
my @nums;
while (1) {
my $in = <>; # read one line
last unless $in =~ m/^\d+$/; # only numbers
push @nums, $in;
}
next unless @nums;
my $sum;
$sum += $_ for @nums;
say $sum;
}
}