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

sort { _compare($obj, $a, $b) } @stuff
  • Comment on Re: Sort mechanics problems with objects and potentially contradicting comparisons (would cause infinite loop)
  • Download Code

Replies are listed 'Best First'.
Re^2: Sort mechanics problems with objects and potentially contradicting comparisons (would cause infinite loop)
by anonymized user 468275 (Curate) on Jun 01, 2016 at 15:57 UTC
    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

      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

      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.

      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