Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: my $cache = undef if undef;

by Tanktalus (Canon)
on Jan 26, 2005 at 17:04 UTC ( #425283=note: print w/ replies, xml ) Need Help??


in reply to my $cache = undef if undef;

It's someone being less clever than they think they are. They think that:

  • $cache being assigned undef is an expensive operation, so by using "if undef", which is always false, we'll save on the actual assignment, and since perl already guarantees an uninitialised variable to be undef, it'll still be undef. This is supposedly more readable since you can still see $cache is set to undef. I would disagree - the "if undef" part is just plain confusing and should be removed. Whether you want to leave the assignment, "= undef", or not, is a matter of personal taste. In cases like this, I probably would leave it in, again, to make it explicit, but others like to play golf a bit more than I do, and would tell you to remove it, too - doesn't really matter.
  • The original author also thought that this would have $cache be static or something, and so we'd generate the cache only once, no matter how many times it's called. They're definitely wrong here, too. A couple of options - move the "my $cache" line to outside the sub, or do that and also put braces around the whole thing. As an example of the latter:
    { my $cache = undef; sub IsMatrix { shift if UNIVERSAL::isa($_[0], __PACKAGE__); my ($child, $parent) = @_; unless ($cache) { my %cache; @cache{@matrices} = (1) x scalar(@matrices); $cache = \%cache; } + return $cache->{"${child}_$parent"}; } }
    The outter braces are the optional part. With them, $cache is only visible inside IsMatrix, without them, the variable is visible to the entire file. With the braces is closer to the original author's intent, but I'm not sure the original author's intent is really that important given these mistakes ;-)
Hope that helps.


Comment on Re: my $cache = undef if undef;
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2014-08-22 06:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (148 votes), past polls