我试图在Perl中动态存储和打印变量,方法是要求用户输入要创建的变量数量,然后要求每个创建的变量添加信息,然后输出每个变量中包含的文本长度。在我的脑海中,我想到了这个:
use strict;
use warnings;
sub main {
my %VarStore = ();
print ("How many variables to create: ");
chomp(my $varNum = <STDIN>);
my $counter = 1
while ($counter <= $varNum) {
print "Enter text to variable $counter: \n";
chomp(my $buffer = <STDIN>);
$VarStore{'var'$counter} = $buffer;
$counter ++;
}
while ($counter <= $varNum) {
print "Variable $counter is length($VarStore{'var'$counter}) character long \n";
$counter ++;
}
}
我想要的是:
> How many variables to create: 3
> Enter text to variable 1: ABCQWEPOL
> Enter text to variable 2: xJSAG!HHKSKASK
> Enter text to variable 3: KakA
> Variable 1 is 9 character long
> Variable 2 is 14 character long
> Variable 3 is 4 character long
任何线索为何我的代码无法正常工作?我在这里想到了一个哈希,这样我就可以根据用户提供的创建变量的键var1,var2,var3等来创建动态变量。预先感谢。
答案 0 :(得分:8)
您是正确的,哈希可以很好地解决此问题。您的代码中有两个问题。首先,$VarStore{'var'$counter}
是无效的语法,您需要使用.
运算符来连接字符串$VarStore{'var'.$counter}
,或者可以使用双引号将变量插值到字符串$VarStore{"var$counter"}
中。 / p>
与变量不同,您不能直接将函数调用内插到字符串中,因此应该单独进行length()调用。或者,您也可以将字符串与函数调用连接在一起。 print "Variable $counter is " . length($VarStore{"var$counter"}). " long\n";
第二个问题是,在您的第一个while循环完成后,您在下一个while循环中重用的$ counter变量将已经大于$ varNum,因此您需要将其重置为1。$counter = 1;
使用foreach loops遍历计数可能更简单。另外,不需要sub main,但是如果使用sub main,则需要实际在某个地方调用main();
才能运行。
use strict;
use warnings;
my %VarStore;
print ("How many variables to create: ");
chomp(my $varNum = <STDIN>);
foreach my $counter (1..$varNum) {
print "Enter text to variable $counter: \n";
chomp(my $buffer = <STDIN>);
$VarStore{"var$counter"} = $buffer;
}
foreach my $counter (1..$varNum) {
my $length = length($VarStore{"var$counter"});
print "Variable $counter is $length character long \n";
}