Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

uninitialized value $_

by Anonymous Monk
on Mar 28, 2016 at 16:18 UTC ( [id://1158961]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I know I am missing some very basic concepts (but that is why I am here). Trying to create a simple program that echoes entered text to a file (and stops when a blank line is entered). So I wrote:
#!/usr/bin/perl use strict; use warnings; my $file = "/path/to/some/file"; open ( FILE, '>', $file ) or die "Can't open $file for writing.\n"; while () { <>; last unless /\S/; print FILE; } close FILE or die "Can't close $file.\n";
But that just gets me:
Use of uninitialized value $_ in pattern match (m//) at...
Where and how do I initialize that?

Replies are listed 'Best First'.
Re: uninitialized value $_
by Corion (Patriarch) on Mar 28, 2016 at 16:21 UTC

    See readline. If the filehandle (or STDIN in your case) gets closed, readline returns undef.

    Your loop is easier written in Perl as:

    while( <> ) { last unless /\S/; print FILE; };
      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; }
        <>; just reads a line and throws it away. Perhaps you meant $_ = <>;?
Re: uninitialized value $_
by shadowsong (Pilgrim) on Mar 31, 2016 at 15:50 UTC

    In addition to what Corion has imparted; once you understand what was causing the error - here is a one-liner you may use that echoes input to filename.txt and stops when a blank line is entered:

    perl -pe "last if /^\s*$/" > filename.txt

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1158961]
Approved by stevieb
Front-paged by Marshall
help
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found