Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

this doesn't sort

by hsfrey (Beadle)
on Feb 26, 2012 at 01:46 UTC ( [id://956164]=perlquestion: print w/replies, xml ) Need Help??

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

I have an array of arrays. I want to sort the arrays based on one element, with index $sortNdx. The following code compiles OK, but doesn't do anything. The array is left unchanged. Any suggestions as to why?
@sorted = sort {$bigArray[$a][$sortNdx] <=> $bigArray[$b][$sortNdx]} @ +bigArray; @bigArray = @sorted;

Replies are listed 'Best First'.
Re: this doesn't sort
by BrowserUk (Patriarch) on Feb 26, 2012 at 01:51 UTC

    Use:

    @bigArray = sort { $a->[$sortNdx] <=> $b->[$sortNdx] } @bigArray;

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

      Yes, That did it perfectly! :-) Thank you!

      But I don't understand it! I can't even make syntactic sense out of it. :-(

      I tried replacing $a->[$sortNdx] with [$a][$sortNdx], which I thought would be syntactically the same thing, but got a syntax error.

      Could you explain to me what's going on?

      Thanks.

        Inside the sort block, $a and $b are elements of @bigArray, not indexes into it.

        So if @bigArray contains array refs, both $a and $b end up being an array ref. And you can dereference and index into an array with the $a->[$index] syntax.

        On the other hand if you write [$a], you wrap the array ref in $a into another array ref -- not what you want.

        See perlreftut and perlref for more details.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://956164]
Approved by BrowserUk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-23 20:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found