perl - How do I print a hash in the same order the elements were added? -
is possible utilize hash in lifo or fifo way? how can create sure hash printed in same order elements added?
#!/usr/bin/perl print "content-type: text/html \n\n"; # origin hash %coins = ( "quarter" , .25, "dime" , .10, "nickel", .05 ); # print old hash while (($key, $value) = each(%coins)){ print $key.", ".$value."<br />"; } # add together new element pairs $coins{penny} = .01; $coins{halfdollar} = .50; # print new hash print "<br />"; while (($key, $value) = each(%coins)){ print $key.", ".$value."<br />"; }
this gives
nickel, 0.05 dime, 0.1 quarter, 0.25 nickel, 0.05 dime, 0.1 halfdollar, 0.5 penny, 0.01 quarter, 0.25
you can either maintain separate array of hash keys, can write
my @coins = qw/ quarter dime nickel penny halfdollar /; $key (@coins) { print "$key, $coins{$key}<br />\n"; }
or can install , utilize tie::ixhash
module, maintain hash elements in order inserted, this
use strict; utilize warnings; utilize tie::ixhash; tie %coins, 'tie::ixhash'; print "content-type: text/html \n\n"; %coins = ( quarter => 0.25, dime => 0.10, nickel => 0.05, ); while (my ($key, $value) = each %coins){ print "$key, $value<br />\n"; } $coins{penny} = .01; $coins{halfdollar} = .50; print "<br />\n"; while (my ($key, $value) = each(%coins)){ print "$key, $value<br />\n"; }
perl
No comments:
Post a Comment