; chomp @arr; It continues to receive input from ...">

Accept user input in Perl

When i use this code

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

It continues to receive input from the user until I use ctrl+z , and then press enter. I want to limit the amount entered by the user in the list. For this I tried

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

But this aging gets into an infinite loop, and I have to use ctrl+c

How can I limit my loop so that only 10 input users enter

+6
source share
1 answer

The main problem is that you use @arr[$i] when you must use $arr[$i] . Using the sigil @ array, you apply the list context in the file descriptor, which forces it to read as many values ​​as possible. When in a scalar context it just reads one value and then proceeds to the next iteration. In other words, it should be like this:

 $arr[$i] = <STDIN>; 

However, you can say a lot about your code. For example, it’s not necessary to use a specific index when assigning numbers, you can just use push

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

Make sure you keep the scalar context. Technically, you can do push @arr, <STDIN> , but that again puts the file descriptor in the list context. This method is pleasant and readable.

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

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

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

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

... your program is now scalable.

In most cases, the use of STDIN is not specifically required or required. For example, you might want your program to also work with a file name as input. Using the "diamond operator" <> allows Perl to independently decide whether to read from <ARGV> or <STDIN> . So you can use:

 my $num = <>; 

You should always use

 use strict; use warnings; 

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

+10
source

Source: https://habr.com/ru/post/954493/


All Articles