Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re^2: loop surprise

by AnomalousMonk (Chancellor)
on Apr 03, 2018 at 18:20 UTC ( #1212273=note: print w/replies, xml ) Need Help??

in reply to Re: loop surprise
in thread loop surprise

It is very common for various implementation quirks to be used with regard to loops, in the very-important name of efficiency.

Rather than efficiency, I think reliability (or perhaps one should better say coherence) is the key concern. If a topicalized (i.e., localized and aliased) Perl-style loop iterator were left un-de-localized upon exit from the loop, to what would it be aliased? An arbitrary element of some named or referenced array? An item in a temporary list, perhaps a literal (i.e., something unwritable), or the (writeble) return value of a function call? (This point has been touched upon in other replies.) Such a state of affairs seems like a recipe for some very perplexing bugs.

IOW, if not de-localized, exactly what is the nature of the thing to which  $_ would remain aliased after loop exit in this code:

c:\@Work\Perl\monks>perl -wMstrict -le "sub F { return 4; } sub G { return 5; } sub H { return 6; } ;; for (F(), G(), H()) { ++$_; printf qq{$_ }; } " 5 6 7
And why would one want to do that?

Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^3: loop surprise
by RonW (Parson) on Apr 05, 2018 at 20:43 UTC
    if not de-localized, exactly what is the nature of the thing to which $_ would remain aliased after loop exit

    Aliasing is an implicit reference to the object that is aliased. Like any referenced object, it would remain until all references to it have been removed.

    As for why, to see what was last processed. Sure, you could use an extra variable, but doing so adds more opportunities for introducing bugs.

    Besides, according to Larry, laziness is a virtue.

      But there is already an extra variable conceptually. $current_iterator != $last_iterated, even when they happen to be the same number/item, they are not logically the same concept. I think the possibility of introducing bugs is much larger where the iterator alias is a repurposed package variable instead of block scoped.

Re^3: loop surprise
by Anonymous Monk on Apr 04, 2018 at 10:14 UTC

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2019-06-26 21:53 GMT
Find Nodes?
    Voting Booth?
    Is there a future for codeless software?

    Results (111 votes). Check out past polls.