Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Hmmm: while(), file handle and $_ gotcha

by moritz (Cardinal)
on Mar 06, 2009 at 12:41 UTC ( [id://748838]=note: print w/replies, xml ) Need Help??


in reply to Hmmm: while(), file handle and $_ gotcha

Bare <DATA> outside a while doesn't assign to $_, which is why the output doesn't change in the inner loop. It's the while that does the rewriting trick to while (defined($_=<DATA>)) { ...}, as described in perlsyn.

Replies are listed 'Best First'.
Re^2: Hmmm: while(), file handle and $_ gotcha
by roboticus (Chancellor) on Mar 06, 2009 at 12:59 UTC
    moritz:

    OK, that explains it. (I had an incorrect mental model: I was thinking that <FH> always put the data somewhere, using $_ unless otherwise specified. I don't know how I came to think that, as in hindsight that would be clearly stupid. Oh, well--live and learn!)

    So the correct fix to my program would is to change the inner loop from:

    for my $cnt (0 .. 3) { my $t=<DATA>; print $t; }

    to

    for my $cnt (0 .. 3) { $_=<DATA>; print; }

    so I can avoid unnecessary variables and clutter.

    Thank you!

    ...roboticus
      or
      for my $cnt (0 .. 3) { print scalar(<DATA>); }

        Cool! And then perhaps:

        while (<DATA>) { if ($. % 10 == 1) { print; print scalar(<DATA>) for(0..3); } }

      Hold up. How does one variable - two, if you did what I do and use a variable for the outer read as well - equate to clutter? I'd probably remove the unused $cnt if I was going to knock clutter out.

      use Modern::Perl; while (my $line = <DATA>) { if ( $. % 10 == 1 ) { print $line; } for (0 .. 3) { my $important_line = <DATA>; print $important_line; } }

      I realize this is a matter of personal aesthetics, of course. I was just a little confused how declaring and using a variable (and avoiding weird behavior from <DATA>) was better than declaring an unused variable and getting the weird behavior.

        Using a variable is even required if you want to add error checking.

        while (my $line = <DATA>) { if ( $. % 10 == 1 ) { print $line; } for (0 .. 3) { defined( my $important_line = <DATA> ) or die("Premature EOF\n"); print $important_line; } }

Log In?
Username:
Password:

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

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

    No recent polls found