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

Say you have an array with numbers and strings...

@array = qw(1 fred);

and you want to sort it by the second element in the array which is a string, how can this be done?

Thanks

Replies are listed 'Best First'.
Re: sort an array by an specific element
by atcroft (Abbot) on Feb 06, 2005 at 00:01 UTC

    Here is one approach that may work:

    #!/usr/bin/perl -w use strict; my @array = ( [ 1, 'chuck', 'z' ], [ 2, 'paul', 'b' ], [ 3, 'adam', 'c' ], [ 4, 'rob', 'p' ], [ 5, 'julius', 'w' ], [ 6, 'bryan', 't' ] ); foreach my $i ( sort { $a->[1] cmp $b->[1] } @array ) { print join( " - ", @{$i} ), "\n"; }

    If it were a numeric comparison, the cmp above would be replaced by the "spaceship operator" ( '<=>' ).

    When run, the following results were obtained:

    3 - adam - c 6 - bryan - t 1 - chuck - z 5 - julius - w 2 - paul - b 4 - rob - p

    Hope that helps.

    Update: 05 Feb 2005

    Changed variable in loop from $a to $i, to avoid confusion with the variables used by sort.

Re: sort an array by an specific element
by punkish (Priest) on Feb 06, 2005 at 01:39 UTC
    You can sort it numerically or alphabetically, ascending or descending, but you can't sort an array by an element. Perhaps you mean an array of arrays, in which case, see atcroft's response.

    While you are at it, do as Fletch suggested. Read up on perl data structures. They are, after all, the very basis of most all further perl learning.

Re: sort an array by an specific element
by Fletch (Bishop) on Feb 05, 2005 at 23:54 UTC

    Erm, could you be more vauge because I almost understood you're trying to sort something. Lacking more detail (such as an example of what you expect your sorted two element array to look like) the only thing answer you're probably going to get is some variation on "read perldoc -q sort".