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.