Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks

I'm a perl beginner and can't see why this sort doesn't work:

my @sorted_vfs = sort { $a->start() <=> $b->start() } @vfs; foreach my $vf (@sorted_vfs){ print $vf->start(), "\n"; }#end for each
The array @vfs is an array of $vf objects which have a numerical property called start. When i loop around the @sorted_vfs array the $vf objects are not in numerical order.

thanks a lot

Replies are listed 'Best First'.
Re: why doesn't this sort work?
by GrandFather (Saint) on Dec 28, 2010 at 00:53 UTC

    Are you sure the call to start doesn't have side effects and that there is nothing happening between the sort and the loop that uses the sorted data? In particular note that start will be called multiple times for each element of @vfs and that @sorted_vfs contains a copy of each element in @vfs which may be a problem if there are any copy semantics associated with the objects in @vfs.

    If you can't sort the problem out you may need to reduce your code to a small stand alone sample script that demonstrates the issue and come back to us.

    True laziness is hard work
Re: why doesn't this sort work?
by Marshall (Canon) on Dec 28, 2010 at 00:49 UTC
    What happens if you put a print statement into the sort? Use a small @vfs dataset and look what happens.
    my @sorted_vfs = sort {print "a: ",$a->start(), " b: ",$b->start(),"\n"; $a->start() <=> $b->start() } @vfs;
Re: why doesn't this sort work?
by Anonymous Monk on Dec 28, 2010 at 00:39 UTC
    $vf objects are not in numerical order.

    ->start are probably all the same, probably the wrong value, it works for me :)

    #!/usr/bin/perl -- use strict; use warnings; Main( @ARGV ); exit( 0 ); sub Snacks::new { my($s,$n) = @_; return bless \$n, $s; } sub Snacks::start { ${$_[0]} } sub Main { my @vfs = map { Snacks->new(int rand 100) } 1 .. 10; my @sorted_vfs = sort { $a->start() <=> $b->start() } @vfs; print "\n", join ' ', map { $_->start } @vfs; print "\n", join ' ', map { $_->start } @sorted_vfs; print "\n"; } __END__ 8 48 50 42 20 42 99 23 25 83 8 20 23 25 42 42 48 50 83 99
      does a foreach loop guarantee to go through elements in order? perhaps the sort is ok but the foreach loop after is not
        does a foreach loop guarantee to go through elements in order?

        Absolutely