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

Re: Last undefines a for loop's itererator?

by ivancho (Hermit)
on Nov 12, 2005 at 17:24 UTC ( [id://507989]=note: print w/replies, xml ) Need Help??


in reply to Last undefines a for loop's itererator?

after all, you wouldn't want every loop
foreach (0..10) { whatever }
or even
print for @bla;
to clobber up your $_, no? So it sounds logical that the control variable should be localized..

kaif, why don't you use first, from List::Util, if the snippet is small enough?

Replies are listed 'Best First'.
Re^2: Last undefines a for loop's itererator?
by kaif (Friar) on Nov 13, 2005 at 23:30 UTC
    Hmm. I missed this reply to my post for a while since it's not quite a reply to my post. :-)

    I guess I should use first --- I may have to experiment to see if it handles code with side-effects like I would desire. Thanks a bunch.

    (And, yeah, $_-clobbering is, in my experience, something terrible that eventually every beginning Perl programmer runs into and spends hours debugging. Phew!)

Re^2: Last undefines a for loop's itererator?
by jonix (Friar) on Nov 14, 2005 at 11:13 UTC
    OK, I guess your remark confuses me a bit:
    What do you mean with for/foreach clobbering up $_?
    Is $_ not always implicitly localized in these looping constructs as a lexical (while while is not really a looping construct) - what is the problem with using $_?

    Cheers,
    jonix
      $_ is, indeed, localized in for(|each) loops. I was using this to support the claim that any other (explicit) loop variable would be better off localized too. Using $_ is, of course, perfectly fine.
      I quite like ewilhelm's point - if one wants a loop that behaves like a function, why not write one.

      I guess there's some sort of linguistic argument here as well - if we say "This cow is green. Each cow in the field is purple. The cow has red eyes", in the last sentence 'cow' has clearly reverted to mean the first cow again, even though it's been pointing to other cows in the 'Each' sentence..

        Thanks, it seems I simply understood you wrong.
        I often like to pronounce $_ as "it" for myself, as "dollar-underscore" is too long and meaningless. How do you pronounce $_ when talking about it btw.?

Log In?
Username:
Password:

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

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

    No recent polls found