Code Comments
Programming Forum and web based access to our favorite programming groups.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
Post Follow-up to this messageBOLCATO 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
Post Follow-up to this messageOn 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
Post Follow-up to this message
Show a Printable Version
Email This Page to Someone!
Receive updates to this thread
Powered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.