in reply to Sorting on a split hash value

Do you mean something like this...?

Regular expression with capture
$games{person} = "11::Game name::Game date"; foreach (sort keys %games) { my ($count, $rest) = $games{$_} =~ /^([^:]+)::(.*)/; print "<td>$count</td><td>$rest</td>..."; }

Somehow I have a feeling that you are actually looking for a way to sort your hash by each person's score?
use strict; use warnings; use Data::Dumper; my %games; $games{person1} = "11::Game name::Game date"; $games{person2} = "12::Game name::Game date"; $games{person3} = "9::Game name::Game date"; # sort by score, and record sorted list of hash keys my @sorted = map { $_->[0] } sort { $b->[1] <=> $a->[1] } map { [ $_, (split /::/,$games{$_})[0] ] } keys %games; foreach (@sorted) { # my ($count, $rest) = $games{$_} =~ /^(\d+)::(.*)/; # I like thor's split with limit suggestion below, # certainly looks cleaner. my ($count, $rest) = split/::/,$games{$_},2; print "<td>$_</td><td>$count</td><td>$rest</td>...\n"; }


And now combile the Schwartzian transform and the foreach to get the optimized form -
... print "<td>$_->[1]</td><td>$_->[2]</td>...\n" for sort { int $b->[1] <=> int $a->[1] } map { [ $_, split /::/, $games{$_}, 2 ] } keys %games; ...

Replies are listed 'Best First'.
Re: Re: Sorting on a split hash value
by thor (Priest) on Jan 15, 2004 at 13:12 UTC
    If the delimiter is indeed '::', one can use split and pass in a limit.
    ($count, $rest) = split(/::/,$games{$_},2);

    thor