Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I want to sort a hash's %h keys in an arbitrary order @seq. I can achieve that by building a helper hash %seq_helper in which the first key is the first item in @seq and the first value is 0, the second key is the next item in @seq and the second value is 1 and so on. Then I can easily compare the items of @seq using <=> and the values of %seq_helper.
However, it does not seem to be possible to make this into a sorting subroutine that accepts a list that tells the sub how I want the items to be sorted. The following is a syntax error after sort by_seq.
use strict; use diagnostics; sub by_seq { my $seq_aref = shift; my %seq_helper; { my $index = 0; for my $item (@{ $seq_aref }) { $seq_helper{$item} = $index; $index++; }; }; return $seq_helper{$a} <=> $seq_helper{$b}; }; # -- my %h = (one=>2,three=>4,five=>6,seven=>8,nine=>0); for (sort by_seq([qw(five nine one seven three)]) keys %h) { print "$_: $h{$_}\n"; }; __DATA__ expected output five: 6 nine: 0 one: 2 seven: 8 three: 4
➀ Why?
➁ How would you solve it?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: sort in arbitrary order with subroutine, syntax error
by Corion (Patriarch) on Dec 19, 2007 at 10:56 UTC | |
|
Re: sort in arbitrary order with subroutine, syntax error
by moritz (Cardinal) on Dec 19, 2007 at 10:45 UTC | |
|
Re: sort in arbitrary order with subroutine, syntax error
by citromatik (Curate) on Dec 19, 2007 at 10:49 UTC |