in reply to Efficiently sorting array by non-alpha strings

This would do it and is easier to extend than the multiple ifs or an if/else cascade.

#!/usr/bin/perl use strict; use Data::Dumper; my @advocates = ( { fld_title => 'Rec1', fld_type => 'National', }, { fld_title => 'Rec2', fld_type => 'State', }, { fld_title => 'Rec3', fld_type => 'Local', }, ); my $order = "\0local\0state\0national\0"; sub by_locale { index( $order, "\0" . lc( $a->{ fld_type } ) . "\0" ) <=> index( $order, "\0" . lc( $b->{ fld_type } ) . "\0" ) } my @sorted_advocates = sort by_locale @advocates; warn Dumper("unsorted_advocates", \@advocates); warn Dumper("sorted_advocates", \@sorted_advocates);

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
Timing (and a little luck) are everything!

Replies are listed 'Best First'.
Re: Re: Efficiently sorting array by non-alpha strings
by knowmad (Monk) on Feb 20, 2004 at 16:30 UTC

    I added your solution to my benchmark and it comes in side-by-side with my original sort solution. However, yours is ++ for elegance and extendability. Thanks for the input!

    -Wm