For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > July 2004 > Endless Loop









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Endless Loop
Bolcato Chris

2004-07-29, 3:56 pm

This may be a dumb question, but why will this loop not end when nothing is
entered in STDIN?

print "Enter Things:\n";
while (<STDIN> ) {
print "I saw $_";
}
print "The End\n";

If nothing is entered the loop continues.
Output:
I saw red
I saw yellow
I saw
I saw
I saw

Bob Showalter

2004-07-29, 3:56 pm

BOLCATO CHRIS (esm1cmb) wrote:
> This may be a dumb question, but why will this loop not end when
> nothing is entered in STDIN?
>
> print "Enter Things:\n";
> while (<STDIN> ) {
> print "I saw $_";
> }
> print "The End\n";


By "nothing is entered", I assume you mean pressing the Enter key alone. But
that's not "nothing", it's "something" (a blank line, with a \n terminator).
In order for the loop to terminate, it needs to see an eof condition on
STDIN. You can usually signal this on Unix-ish systems with Ctrl-D (or
whatever other character your terminal driver has been set to, typically
with 'stty eof').

Or, if you want the loop to terminate when a blank like is entered, you need
to add something like this inside your loop:

last unless /\S/; # end if only whitespace (or empty) line
James Edward Gray II

2004-07-29, 3:56 pm

On Jul 29, 2004, at 9:23 AM, BOLCATO CHRIS (esm1cmb) wrote:

> This may be a dumb question, but why will this loop not end when
> nothing is
> entered in STDIN?


STDIN is a stream. A blank line does not constitute the end of a
stream. I believe your can signal an end to the stream in most
terminals with control-d.

If we want to check for blank lines, we can do that...

> print "Enter Things:\n";
> while (<STDIN> ) {


chomp; # to remove the newline character at the end
last unless length $_; # end when we see nothing

> print "I saw $_";


print "I saw $_\n"; # update to add newline

> }
> print "The End\n";


Hope that helps.

James

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com