develooper Front page | perl.perl5.porters | Postings from April 2000

$a, $b aliases in sort

Thread Next
From:
Hugo
Date:
April 13, 2000 23:09
Subject:
$a, $b aliases in sort
Message ID:
200004140616.HAA12580@crypt.compulink.co.uk
Witness this:

  crypt% perl-5.6.0 -wl
  @a = (3, 2, 1);
  @b = sort {
    ++$a; ++$b;
    print "@a";
    $a <=> $b 
  } @a;
  print "\@a: <@a>; \@b: <@b>";
  __END__
  4 3 1
  5 3 2
  5 4 3
  @a: <5 4 3>; @b: <3 4 5>
  crypt% 

(Same behaviour, though sorting may compare elements in a different
order, at least back to 5.003_97.)

Is it intended that a sort comparison routine be able to modify the
elements of the list being sorted? If so, I'd like to suggest that
perlfunc:sort should mention that $a and $b are aliases, and warn
of the effect of modifying them.

I noticed this only because a response in clp.moderated suggested:

  @sorted = sort {
    ($a) = $a =~ m|^(?:http://)?(.+)|; # do some-
    ($b) = $b =~ m|^(?:http://)?(.+)|; # thing here...
    $a cmp $b; # return the ASCII sort of the altered things.
  } @list;

Hugo

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