Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://425283]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (7)
As of 2018-06-24 02:40 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.