Hash move is ok

I would like to cross HASH, but one by one. Not at random. Any ideas. For example, I have a hash file something like this ...

our %HASH = (
'rajesh:1700'  =>  Bangalore,
'rajesh:1730'  =>  Delhi,
'rajesh:1770'  =>  Ranchi,
'rajesh:1780'  =>  Mumbai,
'rajesh:1800'  =>  MYCITY,
'rajesh:1810'  =>  XCF,
);

      

and it should print in the same way. I tried with the following but couldn't. Any ideas?

while ( my $gPort = each %HASH)
{
    print "$gPort\n";
}


for my  $gPort ( keys %HASH )
{
    print "$gPort\n";
}

      

+3


source to share


4 answers


Given the keys in your question, simply changing the sort comparator will give the desired result.

for my $gPort (sort keys %HASH) {
  print "$gPort => $HASH{$gPort}\n";
}

      



Note. The above code assumes that all numbers in the keys will be in the same position and have the same length. For example, the key rajesh:001775

will be issued first, not between 1770 and 1780.

+4


source


You can sort and print the hash by ordering VALUE (not keys).



for my $gPort (sort { $HASH{$a} <=> $HASH{$b} } keys %HASH) {
  print "$gPort => $HASH{$gPort}\n";
}

      

+1


source


Take a look at Data :: Dumper . In particular, if you install $Data::Dumper::Sortkeys

, then you will get the dump in sorted order.

As an example:

use Data::Dumper;
$Data::Dumper::Sortkeys = 1;

my %some_hash;

# code to populate hash
[ . . . ]

print Dumper(\%some_hash);

      

Of course this will only work if you just want to flush the hash. If you want to print in a different format, you just need to sort the keys and print, for example

foreach my $key (sort keys %some_hash) {
    print "[KEY]: $key; [VAL]: $some_hash{$key}\n";
}

      

0


source


If you want to preserve the insertion order of your elements in your hash then Tie :: IxHash might be the tool for you. It's very simple:

By showing a simple example:

    use Tie::IxHash;        
    tie my %days_in => 'Tie::IxHash',
            January   => 31,
            February  => 28,
            March     => 31,
            April     => 30,
            May       => 31,
            June      => 30,
            July      => 31,
            August    => 31,
            September => 30,
            October   => 31,
            November  => 30,
            December  => 31;       


      print join(" ", keys %days_in), "\n";        
    # prints: January February March April May June July August
    # September October November December

      

0


source







All Articles