in reply to Re: Sort mechanics problems with objects and potentially contradicting comparisons (would cause infinite loop)
in thread Sort mechanics problems with objects and potentially contradicting comparisons (would cause infinite loop)

That's a way to avoid the undocumented feature, but it is also nonstandard. I'll experiment with a variation though:
sort { $obj->_compare }
which also passes $obj as first parameter and see if I still get $a and $b for free, which IS documented magic. Many thanks for the suggestion.

One world, one people

  • Comment on Re^2: Sort mechanics problems with objects and potentially contradicting comparisons (would cause infinite loop)
  • Download Code

Replies are listed 'Best First'.
Re^3: Sort mechanics problems... (updated)
by haukex (Archbishop) on Jun 01, 2016 at 16:05 UTC
    and see if I still get $a and $b for free

    You can get at them:

    use warnings; use strict; { package Bar; my $obj = Foo->new; print join ", ", sort {$obj->mysort($a,$b,"bar")} qw/x a o/; } { package Foo; sub new { bless {}, shift } use Data::Dump 'pp'; sub mysort { pp \@_; $_[0] cmp $_[1]; } } __END__ [bless({}, "Foo"), "x", "a", "bar"] [bless({}, "Foo"), "x", "o", "bar"] [bless({}, "Foo"), "o", "a", "bar"] x, o, a

    Updated example: Previously I had mysort reaching into the main package via $::a, which is obviously not the best solution, now I'm passing $a and $b as parameters. (I see the AM made the same suggestion.) Update 2: There are other solutions possible as well.

    Hope this helps,
    -- Hauke D

Re^3: Sort mechanics problems with objects and potentially contradicting comparisons (would cause infinite loop)
by ikegami (Patriarch) on Jun 01, 2016 at 16:52 UTC

    That makes things far more complicated. Because _compare is likely to be in a package other than the sort, _compare would have to use ${ caller.'::a' } and ${ caller.'::b' } instead of $_[0] and $_[1]. Best to pass $a and $b are arguments.

Re^3: Sort mechanics problems with objects and potentially contradicting comparisons (would cause infinite loop)
by Anonymous Monk on Jun 01, 2016 at 16:06 UTC

    If you pass $a and $b explicitly, you might be able to reuse that sub outside of sort. The "efficiency" of the implicit $a and $b is not really a big deal.

    $obj->_compare($a,$b)
      It's not about efficiency. If $a and $b can't be relied on, any such use of the sort mechanism becomes definitively non-standard and the sort keyword would have to be avoided.

      One world, one people

        They can be relied on, but they have scoping problems and can be confusing when your program spans multiple packages (see hakuex's edit).