1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#!/usr/bin/perl use strict; use warnings; use diagnostics; my %test = ( sup => [ { name => 'Fooname', ident => 'foo', }, { name => 'barname', ident => 'bar', }, ], ); my $match = map {$_->{ident} eq 'bar' ? $_->{name} : ''} @{$test{sup}}; print "'$match'\n";
1 2
my @match = map {$_->{ident} eq 'bar' ? $_->{name} : ''} @{$test{sup}}; print "'$_'\n" for @match;
1 2 3 4
my ($match) = map { $_->{name} } grep { $_->{ident} eq 'bar' } @{ $test{sup} };
1 2 3
my ($match) = map { $_->{ident} eq 'bar' ? ($_->{name}) : () } @{ $test{sup} };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#!/usr/bin/perl use strict; use warnings; use diagnostics; use Benchmark qw(:all); my %test = ( sup => [ { name => 'Fooname', ident => 'foo', }, { name => 'barname', ident => 'bar', }, ], ); print cmpthese(1000_000, { 'map+grep' => sub { my ($match) = map{$_->{name}} grep{$_->{ident}eq'bar'} @{$test{sup}}; }, 'map list' => sub { my ($match) = map{$_->{ident}eq'bar'?($_->{name}):()} @{$test{sup}}; }, }); __END__ Rate map+grep map list map+grep 529661/s -- -7% map list 572410/s 8% --
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
package main; use strict; use warnings; my %test = ( sup => [ { name => 'Fooname', ident => 'foo', }, { name => 'bardame', ident => 'bar', }, ], ); my @match = map {$test{sup}[$_]{ident} eq 'bar' ? $test{sup}[$_]{name} : ''} (0.. scalar @{$test{sup}} - 1); print "@match \n";
1 2 3
my @match = map {$test{sup}[$_]{ident} eq 'bar' ? $test{sup}[$_]{name} : 'KA'} (0.. scalar @{$test{sup}} - 1); print "@match \n"; # KA bardame
2013-08-24T09:38:39 rostimap{} liefert Dir ein Array, hier schonmal ein Fehler im Kontext ;)