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.