Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^6: Use of "my" after Perl v5.14

by AnomalousMonk (Abbot)
on Sep 21, 2012 at 08:51 UTC ( #994853=note: print w/ replies, xml ) Need Help??


in reply to Re^5: Use of "my" after Perl v5.14
in thread Use of "my" after Perl v5.14

use v5.14; { my $count = 1; sub counter { say $count++; } } counter(); counter(); counter(); counter();

Unfortunately, this approach hides a subtle pitfall — well, subtle enough, at any rate, to catch me more than once. The problem is here illustrated:

>perl -wMstrict -le "use v5.14; ;; counter(); counter(); ;; { my $count = 42; ;; sub counter { say $count++; } } ;; counter(); counter(); " 0 1 42 43

There is a critical dependence upon order of execution. The  $count lexical variable is created at compile time, so the  counter() function has no problem accessing it; the code runs with warnings and strictures fully enabled. The variable is not initialized within its closure until some moment during run time; this moment may precede or follow any invocation of the function that quite happily accesses the variable. KaBoom!

It's pretty easy to avoid this problem: perhaps the easiest way is to just use a state variable! But the first step toward avoidance is awareness.


Comment on Re^6: Use of "my" after Perl v5.14
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2014-12-28 06:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (178 votes), past polls