ferment has asked for the wisdom of the Perl Monks concerning the following question:
I have a hash containing keys that refer to particular benchmarks. The hash is populated from a file, and each file contains a baseline benchmark to which the other benchmarks are compared. The set of baseline benchmarks is known and listed in @BASELINES. The hash should always contain exactly one such baseline benchmark.
Needing to both get the baseline and test that exactly one baseline is defined, I wrote something like:
my ($baseline, $oops) = grep { defined } @benchmarks{@BASELINES}; if(not defined $baseline) { die "No baseline case in file" } elsif(defined $oops) { die "Multiple baseline cases in file" }
This works, as far as it goes. However, testing for the definition of the values in the hash creates the corresponding key. Presumably this is because the slice elements are aliases to the original hash, and grep operates on $_, which is also an alias back to the original value. I'm still confused that just testing for definition is enough to create the key, though.
To get around the problem I've used sort in place of grep, sorting so that the defined values appear first:
my ($baseline, $oops) = sort { defined $a ? defined $b ? 0 : -1 : 1 } +@benchmarks{@BASELINES};
This achieves the same effect in this case, and avoids creating the keys, presumably because I'm not using $_ any longer. It's probably less efficient, though, and is not as easy to understand. What I'd really like to know is:
|
|---|