Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: declaring same variable

by markov (Scribe)
on Jan 20, 2004 at 17:26 UTC ( #322643=note: print w/ replies, xml ) Need Help??


in reply to declaring same variable

"my @x if condition" is quite dangerous, because it creates a kind of global variable with restricted scope! If this is in a subroutine, the second time you call the sub, you get exactly the same array, not a new one.

But anyway.. this switch-like initiation is very common, and I like to write it like this:

my @xxx = $op eq 'numbers' ? (one, two, three)
        : $op eq 'alpha'   ? (four, five)
        : $op eq 'alp'     ? (six, ten)
        : die;   # or ()
Just one of many ways to express the same.


Comment on Re: declaring same variable
Download Code
Re: Re: declaring same variable
by davido (Archbishop) on Jan 21, 2004 at 09:44 UTC
    While that code snippet is correct, the first paragraph of explanation is actually partially wrong.

    .... it creates a kind of global variable with restricted scope! If this is in a subroutine, the second time you call the sub, you get exactly the same array, not a new one.

    This is not true. Look at the following:

    use strict; use warnings; sub mytest { my $var if 0; $var++; print $var, "\n"; } mytest(); mytest(); __OUTPUT__ 1 1

    We see several important things in that snippet. First, there are NO errors under strictures, and no warnings. Second, $var is NOT the same variable each time mytest() is called. If we had created a closure, the output would have been 1 and 2, not 1 and 1. If we had autovivified a global, we would have gotten a strictures error, or at minimum, the output would have been 1 and 2. But none of that happens. We get a new lexical variable each time mysub() is called.

    Why?

    Because my has two elements to how it works. First, the compiletime side. At compiletime, the framework is made for a lexical variable. Yet at compiletime, it is too soon to know the outcome of program logic. So the lexical is created without any regard for logic; all that matters is lexical scope.

    At runtime, logic springs to life. And if the "my" declaration has an assignment component to it, as in  my $x = 10 if $condition; that assignment will only take place if $condition is true. But $x exists within the lexical block whether or not $condition is ever true. And it falls out of scope just like any good lexical would, when the lexical block ends, even if its a subroutine.


    Dave

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (12)
As of 2014-10-22 07:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (114 votes), past polls