Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

read a few lines, put them into named variables

by merlyn (Sage)
on Dec 15, 2000 at 07:12 UTC ( #46782=snippet: print w/replies, xml ) Need Help??
Description: 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: snippet [id://46782]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2022-05-18 00:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (68 votes). Check out past polls.

    Notices?