develooper Front page | perl.perl5.porters | Postings from June 2009

[PATCH-DOC] Re: [perl #54040] Misparsing of sort comparisonsubroutine intention

Thread Previous | Thread Next
From:
Bram
Date:
June 28, 2009 03:48
Subject:
[PATCH-DOC] Re: [perl #54040] Misparsing of sort comparisonsubroutine intention
Message ID:
20090628124751.8skgtprkro4c8kgg@horde.wizbit.be
Citeren Ken Williams <perlbug-followup@perl.org>:
> -----------------------------------------------------------------
> [Please enter your report here]
>
> I was surprised by the following behavior of the parser, which
> misinterprets the union() subroutine call as a SUBNAME comparison
> routine for the sort() function:
>
> ==================
> % cat c2.pl
> use strict;
> my %one = qw(a 1 b 2 c 3);
> my %two = qw(a 1 c 2 e 3);
> sub union {
>   my %h;
>   $h{$_}++ for @_;
>   keys %h;
> }
> foreach my $k (sort union(keys(%one), keys(%two)) ) {
>   print "$k\n";
> }
>

The rt ticket has some examples to improve the documentation but noone  
submited a patch.

Attached is a patch that adds:

'
Warning: Care is required when sorting the list returned from a function.

If you want to sort returned by the function call: find_records(@key)  
then you can use:
     @contact = sort { $a cmp $b } find_records @key;
     @contact = sort +find_records(@key);
     @contact = sort &find_records(@key);
     @contact = sort(find_records(@key));

If instead you want to sort the array @key with the comparison routine  
find_records then you can use:
     @contact = sort { find_records() } @key;
     @contact = sort find_records(@key);
     @contact = sort(find_records @key);
     @contact = sort(find_records (@key));
'

Best regards,

Bram


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About