in reply to Re: [perlre/perlgolf] Golf this: return -1 or return +1 on regexp subroutine please
in thread [perlre/perlgolf] Golf this: return -1 or return +1 on regexp subroutine please

Corion,
the algorithm in your sort sub doesn't do what princepawn wants : put 'Organization' before 'Services' before 'FAQ' (and not care about anything else...) .
In fact, if you're sorting a list based only on these, the function will always return 1, because the first match will always be true.
I think the best you could reduce this to (excluding the transform you mentioned, which I'm unfamiliar with) would be a foreach loop, like so (shows pp's implementation, yours and mine) :

#! perl -l my @foo =( "Service", "Organization", "FAQ"); my @priorities = qw(Organization FAQ Service); my $prio_top = join "|", map { "^$_" } @priorities; print join " ", sort by_priority @foo; print join " ", sort boo @foo; print join " ", sort corion @foo; sub by_priority { 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 ; } sub boo { foreach ("Organization", "Service", "FAQ") { return 1 if $b=~/^\Q$_\E/; return -1 if $a=~/^\Q$_\E/; } return 0; } sub corion { # 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; }

  • Comment on Re: Re: [perlre/perlgolf] Golf this: return -1 or return +1 on regexp subroutine please
  • Download Code

Replies are listed 'Best First'.
Re: Re: Re: [perlre/perlgolf] Golf this: return -1 or return +1 on regexp subroutine please
by Corion (Patriarch) on Oct 31, 2002 at 21:53 UTC

    Ooops - yes, my code does an unstable sort on the categories, because the order of the bail-out is different from what princepawn wanted. I wanted to introduce independence from the order of the input values for the normal strings, and lost it on the categories ...

    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