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

But strangely, the code below which shifts the first parameter magically DWIMmed by getting the right object.

I don't believe you.

perl -e' use strict; use warnings; use Data::Dumper qw( Dumper ); sub _DBsort4create { my $obj = shift; print(Dumper($obj)); 0 } my $csvQ = { x => 123, y => 456 }; for my $csvq ( sort _DBsort4create keys %$csvQ ) { } ' $VAR1 = undef;

If it does happen to return the right object, you are modifying a stack you shouldn't be modifying, which should lead to dire repercussions.

  • 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 02, 2016 at 07:47 UTC
    In your example no object has been blessed

    One world, one people

      Do you really think that adding my $o = bless({}); is going to make a difference? Why? Did you try it?
        It was already blessed in the constructor and all methods including the sort routine are in the same class. I don't understand why you are so surprised under the circumstances. Also, why would they call it bless if it had no magic about it? However, I do expect it has something to do with the inheritance magic as I can't reproduce it in an inherticance free case.

        One world, one people

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

    You're right, ik, the code will not work as the OP claims. @_ does not get set when _DBsort4create is called by sort; it's left holding the argument list of the sub that called sort.

    sub compare { my $x = shift; print "\$a = $a, \$b = $b, \$x = $x, \@_ = @_\n"; $a cmp $b; } sub test { sort compare 'z','a','b' } my @z = test('foo', 'bar', 'baz'); print "\@z = @z\n"; output: $a = z, $b = a, $x = foo, @_ = bar baz $a = a, $b = b, $x = bar, @_ = baz $a = b, $b = z, $x = baz, @_ = @z = a b z