Tuesday, September 4, 2012

How can you sort the keys of a Hash numerically?

#!/usr/bin/perl

%FM = ( '91.1' => 'Radio City',
              '92.7' => 'Big FM',
              '93.5' => 'Red FM',
              '94.3' => 'Radio One',
              '98.3' => 'Radio Mirchi',
              '104.0' => 'Fever',
              '104.8' => 'Oye FM',
              '107.1' => 'FM Rainbow',
              '100.7' => 'FM Gold');

for $key ( sort {$a<=>$b} keys %FM )
{
        print "$key->$FM{$key}\n";
}

or

foreach ( sort { $a <=> $b } keys(%FM) )
{
    print "$_ = $FM{$_}\n";
}

No comments :