in reply to [perlre/perlgolf] Golf this: return -1 or return +1 on regexp subroutine please
I'm not sure what algorithm sort uses, but in general, it's a bad idea not to implement identity whenever you write a comparision function.
In your example, the function will always return -1 for the three sets of identical pairs - something that will result in interesting sort orders, depending on the algorithm used.
You should at least rewrite the routine like this :
sub by_priority { # Return 0 on string identity return 0 if $a eq $b; return -1 if $a =~ /^Organization/ ; return 1 if $b =~ /^Organization/ ; return -1 if $a =~ /^Service/ ; return 1 if $b =~ /^Service/ ; return -1 if $a =~ /^FAQ/ ; return 1 if $b =~ /^FAQ/ ; return 0 ; }
My personal favourite when rewriting that code would be via grep :
my @priorities = qw(Organization FAQ Service); my $prio_top = join "|", map { "^$_" } @priorities; sub by_priority { # Return 0 on string identity return 0 if $a eq $b; return -1 if $a =~ /$prio_top/o; return 1 if $b =~ /$prio_top/o; # Alphabetical sort for the rest return $a cmp $b; }
If you're concerned with raw sort speed (for many values), a Guttman-Rosler-Transform would be the best thing - you simply encode the priorities together with each item in a string, let sort rip through it and unpack it afterwards.
If you're not tied to your current algorithm, it might be a good idea to first partition your dataset into the four categories, indivitually sort them and afterwards simply concatenate them together.
perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: [perlre/perlgolf] Golf this: return -1 or return +1 on regexp subroutine please
by boo_radley (Parson) on Oct 31, 2002 at 21:43 UTC | |
by Corion (Patriarch) on Oct 31, 2002 at 21:53 UTC |