Maybe map isn't what you want:
my %b; foreach (@a) { $b{$_} = 1 if defined $_ }
Using foreach is probably faster anyhow. FWIW:
use Benchmark ':all'; my @a; push @a, rand(500) for (0..1000); #build array $a[int(rand(1000))] = undef; #delete an element (sort of) $a[int(rand(1000))] = undef; #delete an element (sort of) cmpthese( 1_000, { 'map' => sub { my %b = map{ $_ => 1 } @a }, 'foreach' => sub { my %b; foreach(@a) { $b{$_} = 1 if defined $_ } + }, }); __END__ Rate map foreach map 374/s -- -44% foreach 673/s 80% --
Note: with warnings on, the map is even slower, because a warning is generated every time an undefined value is encountered in the array. I turned warnings off after discovering this, and so the numbers above represent a sort of best-case.
In reply to Re: from array to hash
by radiantmatrix
in thread from array to hash
by jeanluca
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |