CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [spuds] Manipulating a Hash with keys that have more than one value: Edit Log



Karazam
User

Mar 19, 2011, 2:37 PM


Views: 5619
Re: [spuds] Manipulating a Hash with keys that have more than one value

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:


Code
unless ( $seen{ $aref->[1] } ) { 
push @sorted, [ $aref->[0], $aref->[1] ];
$seen{ $aref->[1] }++;
}


And access the data, now in sorted order, by


Code
for my $x ( @sorted ) { 
print "$x->[0] $x->[1]\n";
}


P.S.
With that change, my version of the program now looks like this:


Code
#!/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)


Edit Log:
Post edited by Karazam (User) on Mar 19, 2011, 2:58 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives