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

Re: conditional definition of variables

by rir (Vicar)
on Aug 26, 2008 at 15:24 UTC ( [id://706922]=note: print w/replies, xml ) Need Help??


in reply to conditional definition of variables

my $var="zzz\n" unless defined($var)

This is the problem; the behavior of a my declaration in a statement with a conditional modifier is undefined. This is documented in perldoc perlsyn. Convert that to an unless statement:

unless ( defined $var) { my $var = "zzz\n" }
and you will get predictable behavior, but, probably, not what you want.

I don't know what you are trying to do, but you might consider using a hash to hold the set of variables that may or may not exist.

Be well,
rir

Replies are listed 'Best First'.
Re^2: conditional definition of variables
by JadeNB (Chaplain) on Aug 26, 2008 at 23:20 UTC
    unless ( defined $var) { my $var = "zzz\n" } and you will get predictable behavior, but, probably, not what you want.
    To expand on what you said, the OP should note that, since the my $var inside the unless has nothing to do with the my $var outside, so this code would leave the outer $var alone, whether or not it's defined. As mentioned by betterworld, just omitting the second my (whether you use the unless in modifier or BLOCK form) gives the (probably-)desired effect of modifying the outer $var.

Log In?
Username:
Password:

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

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

    No recent polls found