
Karazam
User
Mar 19, 2011, 2:37 PM
Post #21 of 35
(4740 views)
|
|
Re: [spuds] Manipulating a Hash with keys that have more than one value
[In reply to]
|
Can't Post
|
|
Since you are using references to %rules, that hash will hold the result of your operations. However, a hash is by its nature not sorted. That is, you don't get things out in the same order as you put them in. That's how hashes work. If you want to use the sorted data further, you need to put in a structure that preserves order, that is, an array. So, try this:
unless ( $seen{ $aref->[1] } ) { push @sorted, [ $aref->[0], $aref->[1] ]; $seen{ $aref->[1] }++; } And access the data, now in sorted order, by
for my $x ( @sorted ) { print "$x->[0] $x->[1]\n"; } P.S. With that change, my version of the program now looks like this:
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my $path = ''; my $cConn = ''; my @sorted; get_rules( $path, $cConn ); for my $aref ( @sorted ) { print "$aref->[0] $aref->[1]\n"; } sub get_rules { my ( $path, $cConn ) = @_; my %rules; # replace this part with your own code to populate the hash while (<DATA>) { my ( $file, $data, $rulenumber ) = split; $rules{$file} = [ $data, $rulenumber ]; } get_sorted_rules( \%rules ); } sub get_sorted_rules { my $href = shift; my %seen; for my $aref ( sort_rules($href) ) { unless ( $seen{ $aref->[1] } ) { push @sorted, [ $aref->[0], $aref->[1] ]; $seen{ $aref->[1] }++; } else { print STDERR "Oh no! Duplicate rule numbers: $aref->[0] $aref->[1]\n"; die; } } } sub sort_rules { my $href = shift; map $_->[0], sort { $a->[1] <=> $b->[1] } map [ [ $_, @{ $$href{$_} }[0] ], @{ $$href{$_} }[1] ], keys %{$href}; } __DATA__ dRule rulenumber=4 4 bRule rulenumber=2 2 cRule rulenumber=3 3 aRule rulenumber=1 1
(This post was edited by Karazam on Mar 19, 2011, 2:58 PM)
|