Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Internally, how do for() and while() differ?

by LanX (Saint)
on Oct 27, 2015 at 00:59 UTC ( [id://1146046]=note: print w/replies, xml ) Need Help??


in reply to Internally, how do for() and while() differ?

for iterates over a list, everything in brackets is expanded (the only exception are ranges ). So <> will create a temporary list.

while loops as long a boolean expression is true.

This can be used together with an iterator, like while($x=iter()) .

There is no general automatism to set $_ like your example implies, that's just magic behavior of the file iterator <> in scalar context. that boolean context.

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!

Replies are listed 'Best First'.
Re^2: Internally, how do for() and while() differ?
by Anonymous Monk on Oct 27, 2015 at 01:23 UTC
     There is no general automatism to set $_ like your example implies, that's just magic behavior of the file iterator <> in scalar context.

    Um, not quite, thats part of the magic of while not readline

    $ perl -MO=Deparse,-p -le "while(<>){print}" BEGIN { $/ = "\n"; $\ = "\n"; } while (defined(($_ = <ARGV>))) { print($_); } -e syntax OK $ perl -MO=Deparse,-p -le "while($f=<>){print}" BEGIN { $/ = "\n"; $\ = "\n"; } while (defined(($f = <ARGV>))) { print($_); } -e syntax OK $ echo hi |perl -le "while($f=<>){print}"
    You see  <> in scalar context didn't set $_
      I meant while's scalar context, and only this iterator.

      Should be documented ( perlsyn ? )

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

      UPDATE

      see perlop#IO-Operators :

      > If and only if the input symbol is the only thing inside the conditional of a while statement (even if disguised as a for(;;) loop), the value is automatically assigned to the global variable $_ , destroying whatever was there previously.

Log In?
Username:
Password:

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

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

    No recent polls found