Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Re: Re: Efficiently sorting array by non-alpha strings

by Limbic~Region (Chancellor)
on Feb 20, 2004 at 16:31 UTC ( [id://330589]=note: print w/replies, xml ) Need Help??


in reply to Re: Re: Efficiently sorting array by non-alpha strings
in thread Efficiently sorting array by non-alpha strings

knowmad,
Actually, you can avoid the ST all together, which should be even faster.
#!/usr/bin/perl use strict; use warnings; my @advocates = ( {fld_title => 'Rec1', fld_type => 'National'}, {fld_title => 'Rec2', fld_type => 'State' }, {fld_title => 'Rec3', fld_type => 'Local' } ); my %order = (LOCAL => 'A', STATE => 'B', NATIONAL => 'C'); my @sorted = sort { $order{uc $a->{fld_type}} cmp $order{uc $b->{fld_t +ype}} || $a->{fld_title} cmp $b->{fld_title} } @advocates; print "$_->{fld_title}\n" for @sorted;
Cheers - L~R

Replies are listed 'Best First'.
Re: Efficiently sorting array by non-alpha strings
by Abigail-II (Bishop) on Feb 20, 2004 at 17:34 UTC
    It's even faster if you avoid the sort block, using GRT:
    #!/usr/bin/perl use strict; use warnings; use Benchmark qw /timethese cmpthese/; our @advocates = map {{fld_title => 'Rec' . $_, fld_type => [qw /National State Local/] -> [ra +nd 3]}} 1 .. shift || 1000; our %order = (LOCAL => 'A', STATE => 'B', NATIONAL => 'C'); our %order_r = reverse %order; our (@limbic, @GRT); cmpthese -1 => { limbic => '@limbic = sort {$order {uc $a -> {fld_type}} cmp $order {uc $b -> {fld_type}} or $a -> {fld_title} cmp $b -> {fld_titl +e}} @advocates', GRT => '@GRT = map {{fld_title => substr ($_, 1), fld_type => $order_r {substr $_, 0, 1}} +} sort map {join "", $order {uc $_ -> {fld_type}}, $_ -> {fld_title}} @a +dvocates', }; my $limbic = join " " => map {$_ -> {fld_title}} @limbic; my $GRT = join " " => map {$_ -> {fld_title}} @GRT; die "Unequal\n" unless $limbic eq $GRT; __END__ Rate limbic GRT limbic 61.9/s -- -49% GRT 121/s 95% --
    It does lose the case of fld_type, but that's easily fixable.

    Abigail

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://330589]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-24 18:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found