Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
my %hash = qw/2 21 200 2425 24 244/;
my $i = 0; # or whatever, just testing
my @sortType = ( sub { $a cmp $b }, sub { $a <=> $b } );
foreach ( sort { $sortType[$i]->() } %hash ) {
print "$_\n";
}
my (%h_num, %h_alpha);
map {$h_num{$_}++} (100, 10, 1000, 1);
map {$h_alpha{$_}++} qw/h1n1 h b a/;
foreach (sort sort_alpha_or_num keys %h_num) {
print "$_ - $h_num{$_}\n";
}
foreach (sort sort_alpha_or_num keys %h_alpha) {
print "$_ - $h_alpha{$_}\n";
}
sub sort_alpha_or_num {
if ("$a$b" =~ /^\d+$/) {
return $a <=> $b;
} else {
return $a cmp $b;
}
}
I do have more than one loop because there are multiple hashes (%h_num, %h_alpha) - are you trying to combine the keys from both hashes in one list?ejaggers said:My question leans more toward, "Dynamic Execution". In your example you still have more than one foreach.
sub AlphaNumericSort {
return ($a cmp $b) || ($a <=> $b);
}
sub SortAlphaNumeric {
return ($a <=> $b) || ($a cmp $b);
}
%test=(11,'a',2,'b');
print join(',',sort{($a<=>$b)||($a cmp $b)}keys%test),"\n";
print join(',',sort{($a cmp $b)||($a<=>$b)}keys%test),"\n";