use strict; use warnings; use Data::Dumper; use Benchmark 'cmpthese'; our %friends; our @results; my $counter=0; my @DATA=; chomp @DATA; sub setup_data { my $repeat=shift || 1; for (1..$repeat) { foreach (@DATA) { $friends{++$counter}={}; @{$friends{$counter}}{qw(ID FIRSTNAME LASTNAME HAIR)} = ($counter,split(/,/, $_)); } } print Dumper(\%friends) unless $repeat>1; } sub sickboy { @results=grep ($$_{HAIR}=~ /brown/i && $$_{FIRSTNAME}=~/^j.*/i, @friends{sort keys %friends}); } sub sickboy_rewrite { # Minor rewrite using -> and non superfluous regex, with /o modifier as well @results=grep ($_->{HAIR}=~ /brown/io && $_->{FIRSTNAME}=~/^j/i, @friends{sort keys %friends}); } sub internal_id { # assuming that the ID is contained in the record, as well as being the key # uncomment the next line to see how this could work with your existing code # $friends{$_}->{ID}=$_ foreach keys %friends; @results=sort { $a->{ID} <=> $a->{ID} } #numeric sort grep { $_->{HAIR}=~/brown/i && $_->{FIRSTNAME}=~/^j/i } values %friends; } sub no_internal_id { # assuming there is _no_ way to add an ID to each record, but sort is still after the grep @results=map { $friends{$_} } sort { $a <=> $b } grep { $friends{$_}->{HAIR}=~/brown/i && $friends{$_}->{FIRSTNAME}=~/^j/i } keys %friends; } sub test_and_display { local $\="\n"; sickboy; print Dumper(\@results); sickboy_rewrite; print Dumper(\@results); internal_id; print Dumper(\@results); no_internal_id; print Dumper(\@results); } # for debugging # setup_data; # test_and_display; for my $x (1,10,100,1_000,10_000,10_000) { setup_data($x); print "\n\nBenchmarking hash of ",scalar keys %friends," records.\n"; cmpthese(-30, {sickboy=>\&sickboy, sickboy_rewrite=>\&sickboy_rewrite, internal_id=>\&internal_id, no_internal_id=>\&no_internal_id, }); } __DATA__ John,Brown,red Fred,Flintstone,black Jane,Brown,blond Betty,Rubble,black John,Kennedy,brown Jodi,Brown,brown Bill,Black,blond June,Green,brown John,McEnroe,brown Erin,White,brown Sean,Comb,green Lexius,Luser,black Monty,Python,balding Joe,Bloggs,white Ian,Flemming,red Zoe,Morte,blonde Peter,Phillips,chrome