in reply to Problem with Schwartzian Transform nested in another sort from a different package

The fast access to $a and $b are provided by setting up local variables in the package in which the sort is invoked. You'll have to find a way to correlate the package in which the sort subroutine is compiled with the package in which the sort operator is being executed.

-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.

  • Comment on •Re: Problem with Schwartzian Transform nested in another sort from a different package

Replies are listed 'Best First'.
Re: Re: Problem with Schwartzian Transform nested in another sort from a different package
by sgifford (Prior) on Apr 15, 2004 at 21:24 UTC

    Or get slower lexical variables for $a and $b by providing a prototyping your comparison function and creating my variables to store them in.

    From perlfunc(1):

    sort SUBNAME LIST
    sort BLOCK LIST
    sort LIST
    
      Sorts the LIST and returns the sorted list value.
      ...
      If the subroutine's prototype is "($$)", the ele­
      ments to be compared are passed by reference in
      "@_", as for a normal subroutine.  This is slower
      than unprototyped subroutines, where the elements
      to be compared are passed into the subroutine as
      the package global variables $a and $b (see exam­
      ple below).
    
Re: •Re: Problem with Schwartzian Transform nested in another sort from a different package
by ronald (Beadle) on Apr 15, 2004 at 21:12 UTC
    So my results are the expected behavior?

    I had (perhaps naively) believed the inner sort in Diffpackage::mysort would set up its own localized $a and $b in its package, and the outer sort would have its own $a and $b in main.

    I guess I don't understand the magic behind $a and $b very well. I am attempting to implement your suggestion about correlating package names, though I'm not quite sure I understand what you mean.

    Many thanks for your reply.
      See the output of the following two one-liners:

      perl -MO=Xref -e "my @array = sort { $a <=> $b } ( 2, 8, 3 );"

      perl -MO=Xref = "local ( $a, $b ); my @array = sort { $a <=> $b } ( 2, + 8, 3 );"

      The first example results in crossreference output that essentially makes no mention of $a and $b.

      The second example results in crossreference output that includes $a and $b under the package main namespace.


      Dave

      If you're confused about variables and packages, it sounds like you need to read Coping with Scoping.

      Since sort was there in Perl 4, the mechanism that it uses by default ($a, $b) accesses the package variable of that name in the current package.