Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Empty STDIN does not exit while loop

by Discipulus (Canon)
on May 20, 2017 at 07:37 UTC ( [id://1190700]=note: print w/replies, xml ) Need Help??


in reply to Empty STDIN does not exit while loop

After chomping, check what remains; exit the loop if nothing is found.

last if $line=~/^$/; # or using length..

UPDATE: you can also use last unless $line; to quit the loop, but this breaks if 0 is passed. If 0 is valid you can last unless defined $line; see below Laurent_R.

Additionally if move the chomp inside the loop you can use CTRL-Z to end fidding STDIN

Notice that chomp returns the number of removed chars, not the chomped string (added in the same time of the below answer..). Considering this and avoiding extra variable $line you can have anything in the while condition:

while ( chomp ( $_ = <STDIN>) and length $_){ print " [$_]\n"; }

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^2: Empty STDIN does not exit while loop
by Laurent_R (Canon) on May 20, 2017 at 08:48 UTC
    you can also use last unless $line; to quit the loop, but this breaks if 0 is passed. If 0 is valid you can last unless defined $line;
    The last unless defined $line; statement will not work either, because even if $line is empty, it will still be defined.

    Your original solution, i.e. last if $line=~/^$/; (or length $line ...), is definitely better.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1190700]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-04-20 01:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found