Maybe someone really meant to say that
my $hash = { a => 'b' };
$hash->{$x}
is just a lot more legible, intelligible, and therefor more maintainable than
{a => 'b'}->{$x}
and in terms of programmer time (as opposed to execution time), the former could be a time saver overall. That's probably a matter of personal judgment and taste, but I'd be inclined to agree with it. Especially as you get into larger numbers of hash elements, IMO, keeping the initialization and the fetching of a value as separate statements seems easier and more intuitive, somehow.
Still, now that I've seen the latter idiom (no, I hadn't seen that sort of usage before), I can appreciate its attraction -- it's sort of like a clever substitute for the (chain of) ternary operator(s). Instead of this:
sub some_function
{
my ( $x ) = @_;
return ( $x eq 'foo' ) ? "results for foo" :
( $x eq 'bar' ) ? "results for bar" :
( $x eq 'qaz' ) ? "results for qaz" :
" ... and so on, ad nauseum";
}
there's this:
sub some_function
{
my ( $x ) = @_;
{ foo => "results for foo",
bar => "results for bar",
qaz => "results for qaz",
}->{$x} || "... and so on, ad nauseum";
}
It might be interesting to benchmark those alternatives, since they seem more "equivalent" (in terms of purpose) than the two you tested.
(updated to fix a typo, and to add the following benchmark script:)
and the results:
Rate anonhash ternary
anonhash 64869/s -- -72%
ternary 232475/s 258% --
Well, so much for being clever, I guess. ;)
One last update: I was still curious about "scalability": what happens as more distinct cases are needed? I adjusted my benchmark script by adding seven more hash keys to the anonhash function, and an equivalent set of seven more chained conditionals in the ternary function. Results:
Rate anonhash ternary
anonhash 26893/s -- -87%
ternary 204817/s 662% --
|