Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

take array input from user in Perl

Tags:

perl

When i'm using this code

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

It goes on taking inputfrom user until i use ctrl+z and then press enter. I want to limit the number of user input to the list. For that I have tried

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

But this aging fall in into infinite loop and i have to use ctrl+c

How can i Limit my loop so that only 10 input user will enter

like image 524
insanity Avatar asked Sep 24 '13 10:09

insanity


1 Answers

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.

like image 156
TLP Avatar answered Oct 06 '22 00:10

TLP