in reply to sorting the column of array element

You're being unclear in what kind of data structure you are holding (try dumping it with Data::Dumper). However, I am guessing you have an array of arrayrefs.

The magic variables $a and $b in sort are aliases to the array's elements. Since the element is an arrayref, you need to dereference it. If you were to access the first column normally in your code, you'd say $array[$x]->[0]. Through the aliasing, $array[$x] is equal to $a or $b. Therefore, the correct syntax should be $a->[0]. So,

sort { $b->[0] <=> $a->[0] } @array

might do the trick.

Replies are listed 'Best First'.
Re^2: sorting the column of array element
by sauoq (Abbot) on May 24, 2012 at 11:45 UTC

    However, I am guessing you have an array of arrayrefs.

    ...

    sort { $b->[0] <=> $a->[0] } @array

    Assuming, like you said, an array of arrayrefs—which is a good assumption, I think—this code would try to order the array refs in @array by the first elements contained in the arrays they reference.

    That seems very unlikely to be what he wants.

    Update:

    If he wants to sort the array referenced by $array[0], the code I gave will work. If he wants to sort all of his "columns," he should sort the indexes based on his sorting column using something like:

    my @indexes = sort {$array[0]->[$b] <=> $array[0]->[$a]} (0..$#{$array +[0]});
    And then use the array of sorted indexes to map the sorted order onto the actual columns with something like this:
    my @sort = map { my $a = $_; [ map { $t->[$_] } @indexes ] } @array;

    It's up to him to be sure the "columns" are the same length, of course.

    -sauoq
    "My two cents aren't worth a dime.";
      To clear, i have to sort the $array[0] which is a column of numbers out of three columns of a file.None of the code above works actually...dunno. Thanks
        None of the code above works actually.

        The code I gave you in my first response works fine for me:

        t$ perl -le 'my @o=([3, 1, 2]);print "@{$o[0]}";my @s=sort {$b <=> $a} + @{$o[0]};print"@s";' 3 1 2 3 2 1

        -sauoq
        "My two cents aren't worth a dime.";