Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Here's what's probably a newbie syntax question...
I'm writing a script that sorts a hash of data from an XML file, with a line like so:

foreach my $event (sort by_title $doc->findnodes( '//program' )) {do stuff}

Say I want to sort by date or by size or some other criterion, based on some input. Can I replace "by_title" with some sort of variable so that it sorts by whatever method I want?

Replies are listed 'Best First'.
Re: Sort by what?
by tinita (Parson) on Jul 16, 2004 at 16:44 UTC
    my %sort = ( by_title => \&by_title, by_whatever => \&by_whatever, ); my $var = 'by_title'; for (sort { &{$sort{$var}} } @array) { ... }
      This simpler version
      $var = 'by_title'; # or $var = \&by_title; sort $var @array;
      will work, where $var can be given either the name of the subroutine or a reference to it. If validation of the sub name is necessary, it ought to be done separately from the call to sort.

      We're not really tightening our belts, it just feels that way because we're getting fatter.
Re: Sort by what?
by Art_XIV (Hermit) on Jul 16, 2004 at 17:47 UTC

    In the statement 'foreach my $event (sort by_title $doc->findnodes( '//program' )) {do stuff}', the 'by_title' is the name of a subroutinE that exists elsewhere in your code. This subroutine is telling the sort command how to sort.

    If you want to sort based upon other criteria using the same idiom, then you could make additional subroutines.

    You can find out more on sorting here and by searching this site.

    Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"
      Thanks all! Got it working.