in reply to Re^3: nested <FILE> read returns undefined?
in thread nested <FILE> read returns undefined?

You said:

the important part here is the list context.

As usual, retrospect is 20/20, and now I see it. However, it's easy to see how one can be confused in the first place.

for my $line (<FILE>)

sure looks like scalar context, because $line isn't an array. This is further underscored by the fact that the loop will assign the next "line" to the variable. Because it feels like <FILE> is being read line-by-line, it's easy to see how for is treating <FILE> like a one-item array upon each iteration. Cap it all off with Duff's comment that perl 6 will "do the right thing" by... well, doing what I just described.

So, which is the right(tm) way? The @array context that it's currently doing (that you described)? Or the line-at-a-time way that I described, and that will be part of perl6?

I can see it both ways now, which is why I think the biggest problem is that this very thing isn't spelled out more explicitly in the perl book.

Replies are listed 'Best First'.
Re^5: nested <FILE> read returns undefined?
by tirwhan (Abbot) on Apr 01, 2006 at 08:44 UTC

    I don't think there is a right/wrong way of doing things in this case, just the way a particular language (version) does it. Perl 6 is a very different beast from Perl 5 and I'd guess that what duff describes works because Perl 6 is able to lazily evaluate some things that Perl 5 can't (that's just an uninformed guess though and may be wrong).

    Just a note on the documentation though, the Camel is a great book and invaluable when learning and programming Perl. But it is not AFAIK the reference documentation for Perl, that is in the perldocs and you're really missing out if you don't read those.


    All dogma is stupid.
      just to bring closure on this-- I wasn't necessarily trying to argue that there was a "right way" or "wrong way" so much as saying that there is ambiguity about whether for $scalar (@array) would cause <FILE> to be read in its entirety, or line-by-line. there are many cases where perl looks at lvalue to determine what to do on the right side, and this seems like just such a case at first blush.

      $line = <FILE>; # reads one line from FILE; @lines = <FILE>; # slurps up the whole thing. for $line (<FILE>) ... # which of the above applies?

      The thing that really makes the visual assessment ambiguous is the placement of $line in the for statement, which is the source of the perceived ambiguity. Granted, I only saw it as the scalar form, and I do realize that it'd be more like saying

      for $line (@lines)

      which clarifies how perl is reading it (and thus, what happens with <FILE>), but seeing both ways now makes the ambiguity more understandable.