Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: scoping question

by vladb (Vicar)
on Mar 02, 2006 at 16:38 UTC ( #533964=note: print w/ replies, xml ) Need Help??


in reply to scoping question

Declaring variables once at the beginning of the code block where they are being first used is the best practice imo. One other alternative (yet poor) approach is to use the special $_ variable.

if ( $_ = $obj->get_id() ) { # use $_ inside this block... $obj->do_this(); } elsif ( $_ = $obj->create_id() ) { # use $_ inside this block $obj->do_that(); } else { $obj->do_somethingelse(); }
Generally, however, this wouldn't be a very sound approach, as it is usually very easy to loose track of the $_ variable. Although, it does spare you having to declare variables, especially for short code blocks or loops.

Update: As ikegami pointed out (++), I stress that the use of $_ is a bad idea. I just wanted to show one alternative, albeit a bad one as a means of warning against such approach. :)
_____________________
"We've all heard that a million monkeys banging on a million typewriters will eventually reproduce
the entire works of Shakespeare. Now, thanks to the Internet, we know this is not true." - Robert Wilensky, University of California


Comment on Re: scoping question
Select or Download Code
Re^2: scoping question
by ikegami (Pope) on Mar 02, 2006 at 16:47 UTC
    Don't assign to $_ without localizing it first! $_ is usually aliased to another variable, and your code would clobber it. The fix is to add local to the first assignment (as shown below). However, if you do that, you've gained nothing but obfuscation. You should use my $id instead of local $_.
    if ( local $_ = $obj->get_id() ) # XXX Use "my $id =" instead of { # "local $_ =" for clarity. $obj->do_this(); } elsif ( $_ = $obj->create_id() ) # XXX Use "$id =" instead of { # "$_ =" for clarity. $obj->do_that(); } else { $obj->do_somethingelse(); }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (10)
As of 2014-10-01 07:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (389 votes), past polls