my $hash = { a => 'b' };
$hash->{$x}
####
{a => 'b'}->{$x}
####
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";
}
####
sub some_function
{
my ( $x ) = @_;
{ foo => "results for foo",
bar => "results for bar",
qaz => "results for qaz",
}->{$x} || "... and so on, ad nauseum";
}
####
#!/usr/bin/perl
use strict;
use Benchmark qw(:all);
sub anonhash
{
my ( $x ) = @_;
{ foo => "results for foo",
bar => "results for bar",
qaz => "results for qaz",
}->{$x} || "... and so on, ad nauseum";
}
sub ternary
{
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";
}
my @strings = qw/foo bar baz qaz/;
my $i = 0;
cmpthese( -5, {
anonhash => sub { anonhash( $strings[$i++] );
$i = 0 if ( $i == @strings ) },
ternary => sub { ternary( $strings[$i++] );
$i = 0 if ( $i == @strings ) },
} );
####
Rate anonhash ternary
anonhash 64869/s -- -72%
ternary 232475/s 258% --
####
Rate anonhash ternary
anonhash 26893/s -- -87%
ternary 204817/s 662% --