CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
How to Limit <STDIN> User-Input Entry?

 



mar85
Novice

Mar 21, 2013, 6:20 PM

Post #1 of 3 (390 views)
How to Limit <STDIN> User-Input Entry? Can't Post

Hello,
I've recently practicing to write perl scripts and am trying to write a code to get 5 input entries from the user and store the entries to an array. However, when executed, it seems that it endlessly asking for the user-input, and not 5 times. Below is the code:


Code
my @user_input = (); 
my $i = 0;

#foreach (<STDIN>)
for(my $i=0; $i<5; $i++)
{
chomp;
print "Enter entry no.$i: \n";
push @user_input, <STDIN>;
}

print "@user_input\n";


Is there any mistake in the code?
Thanks


BillKSmith
Veteran

Mar 21, 2013, 8:05 PM

Post #2 of 3 (383 views)
Re: [mar85] How to Limit <STDIN> User-Input Entry? [In reply to] Can't Post


Code
       push @user_input, scalar <STDIN>;


The second of argument of push is a LIST. (Refer perldoc -f push) This imposes list context on <STDIN>. In list context, the diamond operator (<>) reads an entire file.

Your code actually works as you expect if you manually enter an end-of-file character after every input record.
(Under windows, enter one datum, RETURN, and CTRL-Z)

As a matter of style, always use strict and warnings. Seldom (if ever) use the C-style for loop. In this case, I think it is clearer to use a scalar variable to impose scalar context on <>. Use <> rather than the explicit <STDIN> unless you know the difference. Even better, use a prompt module from CPAN.

The following code does not chomp the input becuse the returns are neded in the output.

Code
use strict; 
use warnings;
my @user_input;
for my $i (1..5) {
print "Enter entry no.$i: \n";
my $datum = <>;
push @user_input, $datum;
}
print @user_input, "\n";

Good Luck,
Bill

(This post was edited by BillKSmith on Mar 21, 2013, 8:06 PM)


mar85
Novice

Mar 22, 2013, 12:03 AM

Post #3 of 3 (380 views)
Re: [BillKSmith] How to Limit <STDIN> User-Input Entry? [In reply to] Can't Post

Thank you Bill for the explanantion. Really helps

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives