Hello again Gtforce,
Since you are also interested in speed and resources here is a small Benchmark measurement including three different ways of resolving your problem:
#!/usr/bin/perl use strict; use warnings; # use Benchmark qw( timethese cmpthese ) ; # WindowsOS use Benchmark::Forking qw( timethese cmpthese ); # UnixOS my @array = ("a1 b1", "a2 b2", "a3 b3", "a5 b5", "a4 b4"); sub mapBenchmark { my (@localArray) = @_; my %hash = map { split( / /, $_, 2 ) } @localArray; return \%hash; } sub forBenchmark { my (@localArray) = @_; my %hash; foreach my $element (@localArray) { my ($key, $value) = split(/ /, $element); $hash{$key} = $value; } return \%hash; } sub whileBenchmark { my (@localArray) = @_; my %hash; while (defined(my $element = shift @localArray)) { my ($key, $value) = split(/ /, $element); $hash{$key} = $value; } return \%hash; } my $results = timethese(-10, { 'MapBenchamrk' => sub { mapBenchmark(@array) }, 'ForBenchamrk' => sub { forBenchmark(@array) }, 'WhileBenchamrk' => sub { whileBenchmark(@array) }, }, 'none'); cmpthese( $results ); __END__ $ perl test.pl Rate ForBenchamrk WhileBenchamrk MapBenchamrk ForBenchamrk 219717/s -- -10% -32% WhileBenchamrk 243436/s 11% -- -24% MapBenchamrk 321814/s 46% 32% --
A minor note here, if you use while loop it is a bit faster than foreach loop but it destroys the array.
In conclusion on this case map looks to be the best option and it can be put it like this on a function:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @array = ("a1 b1", "a2 b2", "a3 b3", "a5 b5", "a4 b4"); sub mapBenchmark { my %hash = map { split( / /, $_, 2 ) } (@_); return \%hash; } print Dumper mapBenchmark(@array);
Hope this helps, BR.
In reply to Re^3: search and return values from an array
by thanos1983
in thread search and return values from an array
by Gtforce
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |