in reply to problem while sorting hash

Check out this brief article for inforomation and examples using tied hash modules that preserve ordering.

Depending on your circumstances, it may be more expedient to save your @year array and use that anywhere you need to access your data in order.

$hash_value = { '75.34.42.17511726663' => { # '1995' => [ '', '200,000' ], # Duplicate key, # overwritten by next line '1995' => [ '', '200,000' ], '1996' => [ '3.3', '206,680' ], '1997' => [ '2.6', '212,118' ], '1998' => [ '3.7', '219,980' ], '1999' => [ '4.2', '229,281' ], '2000' => [ '7.7', '247,015' ], '2001' => [ '6.7', '263,645' ], '2002' => [ '7.6', '283,665' ], '2003' => [ '5.4', '298,857' ], '2004' => [ '9.2', '326,345' ], '2005' => [ '11.5', '363,842' ], '2006' => [ '9.4', '398,148' ], } }; # To sort year from the hash @year= sort {$a cmp $b} keys(%{$hash_value->{'75.34.42.17511726663'}}) +; # To do stuff with structure - year ascending order format. my @foo_stuff; foreach $key (@year) { push @foo_stuff, Foo( $hash_value->{'75.34.42.17511726663'}{$key} +); } sub Foo { return @$_[0]; }

In your code you have 1995 twice in your data set. Each key in a hash can only have one value, and only the last inserted value will be kept. If your data set will have multiple entries for each year, you'll need to reconsider your data structure.


TGI says moo

Replies are listed 'Best First'.
Re^2: problem while sorting hash
by Anonymous Monk on Mar 21, 2007 at 03:42 UTC
    Thanks TGI.