in reply to hash sorting/alphabetization issue : country postal codes

my %country_names = ( "AF" => "Afghanistan", "AX" => "Aland Islands", "AL" => "Albania", "DZ" => "Algeria", "AS" => "American Samoa", "AD" => "Andorra", ); my @intl_files = <DATA>; chomp @intl_files; # not needed when using opendir/readdir #map removes the ".txt" file suffix #sort compares country names, not codes my @sorted = sort { $country_names{ $a } cmp $country_names{ $b } } map { substr( $_, 0, rindex( $_, '.' ) ) } @intl_files; foreach my $file ( @sorted ) { print "<option value=\"$file\">$country_names{$file}</option>\n"; } __DATA__ AL.txt DZ.txt AS.txt

Replies are listed 'Best First'.
Re^2: hash sorting/alphabetization issue : country postal codes
by hmbscully (Scribe) on Jul 03, 2007 at 20:06 UTC
    Thank you. I understand the problem in my thinking now. I see that I needed to sort previous to the foreach loop rather than in it. I know there are always multiple ways to do things, but this one makes sense to me.

    I learn more and more about less and less until eventually I know everything about nothing.

      I see that I needed to sort previous to the foreach loop rather than in it.

      No, that's not the problem you were having. And there's no problem with putting the sort inside the foreach statement.

      my @codes = map { substr($_, 0, rindex($_, '.')) } @intl_files; foreach my $code ( sort { $country_names{$a} cmp $country_names{$b} } ) { print "<option value=\"$code\">$country_names{$code}</option>\n"; }