6

当我使用此代码时

print "\nEnter !0 numbers \n\n";
@arr=<STDIN>;
chomp @arr;

它继续从用户那里获取输入,直到我使用ctrl+z然后按回车键。我想限制列表中用户输入的数量。为此我已经尝试过

print "\nEnter !0 numbers \n\n";
for($i=0;$i<10;$i++)
{
@arr[$i]=<STDIN>;
chomp @arr;
} 

但是这种老化陷入无限循环,我必须使用ctrl+c

我如何限制我的循环,以便只有 10 个输入用户将输入

4

1 回答 1

10

The basic problem here is that you are using @arr[$i] when you should be using $arr[$i]. Using the array sigil @, you enforce a list context on the file handle, which makes it read as many values as it can. When in scalar context, it will just read one value and then go to the next iteration. In other words, it should be like this:

$arr[$i] = <STDIN>;

However, lots more can be said about your code. For example, it is quite unnecessary to use a specific index when assigning numbers, you can simply use push

for (1 .. 10) {
    my $num = <STDIN>;
    chomp $num;
    push @arr, $num;
}

Be careful to ensure that you keep the scalar context. Technically, you can do push @arr, <STDIN>, but that will put the file handle in list context again. This way is nice and readable too.

Another way to do the same thing, without using an "external" counter, is using the array itself as the loop condition. When in scalar context, an array returns its size. We can use that with while like this:

while (@arr < 10) {
    my $num = <STDIN>;
    chomp $num;
    push @arr, $num;
}

Now, if you set a variable for your count...

my @arr;
my $count = 10;
print "Enter $count numbers: ";
while (@arr < $count) {

...your program is now scalable.

Most of the time, using STDIN specifically is not required, or desired. For example, you might want your program to work also with a file name as input. Using the "diamond operator" <> allows Perl to decide on its own whether to read from <ARGV> or <STDIN>. So, you might instead use:

my $num = <>;

You should always use

use strict;
use warnings;

These two pragmas has a short learning curve, but coding without them is difficult and hazardous.

于 2013-09-24T10:30:09.843 回答