in reply to help with array of arrays

Thanks for the responses! Actually by just saying my @home each time through the loop, I was able to create an array of seperate references. But now that that is working, why am I having trouble sorting the array?

I have an array of array references, which I want to be sorted by the second element of the referenced array.
foreach my $sort (@sorted){ print "<h1>$sort->[2]</h1>"; } # sort the array of arrays by price @sorted = sort {$main::a->[2] <=> $main::b->[2]} @sorted; foreach my $sort (@sorted){ print "<h1>$sort->[2]</h1>"; }
With this code, the numbers are printed out as follows.

Before Sorting
4,900 1,900 1,333,987

After sorting
1,900 1,333,987 4,900

Those don't seem to be in ascending order to me! Any help is appreciated.

Replies are listed 'Best First'.
Re: Re: help with array of arrays
by Chmrr (Vicar) on Apr 01, 2002 at 02:43 UTC

    Yup, that's sorted. What's tripping you up is the commas. Because you're comparing them using <=>, they get compared in numerical context. Sure enough, "1,900"+0 and "1,333,987"+0 are both 1, so they're at the beginning of the "sorted" list. You may want to uncommify the data when you read it in, and put the commas back in only when you print it.

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

Re: Re: help with array of arrays
by gav^ (Curate) on Apr 01, 2002 at 02:47 UTC
    You need to use strict and warnings. You are trying to compare two things that aren't actually numbers (as they have a comma in them). If you had warnings on you'd get something like:
    Argument "1,900" isn't numeric in sort at sort.pl line 7, <DATA> line +3. Argument "4,900" isn't numeric in sort at sort.pl line 7, <DATA> line +3. Argument "1,333,987" isn't numeric in sort at sort.pl line 7, <DATA> l +ine 3.
    You also don't need to use $main::a and $main::b as $a and $b are special and are globals.

    You probably want to do something like:

    @sorted = sort {$a->[2] <=> $b->[2]} map { s/,//g; $_ } @sorted;
    You might want to look up the Schwartzian Transform or perldoc sort.

    gav^