Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: uninitialized value $_

by Anonymous Monk
on Mar 28, 2016 at 17:04 UTC ( [id://1158965]=note: print w/replies, xml ) Need Help??


in reply to Re: uninitialized value $_
in thread uninitialized value $_

Are you saying that STDIN is getting opened and closed every time a line is read? I guess that would explain why there is nothing there. :) How about a small variation where I need to print something (a prompt or line number) on the terminal before reading the line (so I couldn't have <> in the loop control)? The (broken) code would be something like:
while () { print $foo; <>; last unless /\S/; print FILE; }

Replies are listed 'Best First'.
Re^3: uninitialized value $_
by Paladin (Vicar) on Mar 28, 2016 at 17:16 UTC
    <>; just reads a line and throws it away. Perhaps you meant $_ = <>;?
      That works. I thought (incorrectly obviously) that $_ automatically was assigned the last line read. I recall seeing examples like that, but maybe it was only for reading from files.
        > $_ automatically was assigned the last line 

        That's a special DWIM magic within the while condition only!

        while (<>) {

        ... which is Perl shorthand for the more explicitly written version: ...

        while (defined($line = <ARGV>)) {

        Cheers Rolf
        (addicted to the Perl Programming Language and ☆☆☆☆ :)
        Je suis Charlie!

        Perhaps a better thought model is that $_ gets assigned the last thing read. At the end of the file, that last thing is the EOF, which is returned as undef.

        The fundamental problem here was poor loop design. The use of for(;;){} or while (1){} should be restricted to very special circumstances like an infinite loop in server code to wait for next connection, etc. If the loop is coded differently and I would argue properly, as corion suggests, while (<>){}, this handling undef inside the loop problem goes away.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-03-29 06:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found