Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

read a few lines, put them into named variables

by merlyn (Sage)
on Dec 15, 2000 at 07:12 UTC ( [id://46782]=CUFP: print w/replies, xml ) Need Help??

On IRC a short while back, someone wanted to read precisely 13 lines repeatedly. While a few idioms were tossed around, I stumbled on the one I present here, and it was just too cool not to share with y'all. Enjoy!
$_ = <STDIN> for $one, $two, $three, $four, $five;

Replies are listed 'Best First'.
Re: read a few lines, put them into named variables
by merlyn (Sage) on Dec 15, 2000 at 07:16 UTC
    And just to go a bit further, check this out:
    { defined($_ = <STDIN>) or last for my ($one, $two, $three, $four, $five); .. process all five lines .. redo; }
    This aborts if we ever get less than five lines, and declares them all at once! Cool! For example, alternating lines of key/value pairs:
    { defined($_ = <STDIN>) or last for my ($key, $value); $hash{$key} = $value; redo; }
    And if there's an odd number lines, we don't execute that code for that last line.

    -- Randal L. Schwartz, Perl hacker

Re: read a few lines, put them into named variables
by robsv (Curate) on Feb 22, 2001 at 01:43 UTC
    merlyn,
    This is very cool! I did run into one small quirk in the key/value pair example - it doesn't stop (I think because the last drops out of the for, not the loop block). I got it to work as:
    LOOP: { defined($_ = <STDIN>) or last LOOP for my($key,$value); chomp($key,$value); $hash{$key} = $value; redo; }
    I guess the chomp really isn't necessary, but I wanted to ditch the newlines. Thanks!

    - robsv

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2024-04-16 09:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found