The code block given to sort will not get any arguments (or, if it gets them, the arguments will be $a and $b. If you're not passing a code block as the first argument, you need to list all arguments separated by commas:

for (sort by_seq([qw(five nine one seven three)]), keys %h) {

(except that by_seq won't do what you want yet).

If you want to make the thing work, the easiest way is to generate the comparison subroutine on the fly and use it with sort:

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++; }; }; # Here I return a subroutine that takes two arguments # (the left and the right element to be compared) return sub { $seq_helper{$_[0]} <=> $seq_helper{$_[1]} }; }; # -- my %h = (one=>2,three=>4,five=>6,seven=>8,nine=>0); # Create our custom comparison routine my $sorter = by_seq([qw(five nine one seven three)]); for (sort {$sorter->($a,$b)}, keys %h) { print "$_: $h{$_}\n"; };

I thought I could write sort $sorter, LIST, but that gets interpreted by Perl (rightfully) as sort LIST, so I guess you'll be stuck with the extra code block.


In reply to Re: sort in arbitrary order with subroutine, syntax error by Corion
in thread sort in arbitrary order with subroutine, syntax error by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.