in reply to Re^2: sorting an array with mixed elements...
in thread sorting an array with mixed elements...

You can't split it up completely, but you could write like so

sub compare { (split ":", $a)[0] <=> (split ":", $b)[0] } my @sorted = sort compare @table; print @sorted;

It would also benefit from applying a Schwartzian Transform (ST):

print map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [ (split /:/, $_)[0], $_ ] } @table;

A ST is read from the bottom up

map { [ (split /:/, $_)[0], $_ ] } @table;

creates an anonymous array with the thing you want to sort on as the first element ((split /:/, $_)[0]), and the original line as the second($_)

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

does the sort, using the first element of the arrays you just created

map { $_->[1] }

returns the original line from the second element of your arrays.

There's loads of material on the interweb on the ST if you want to know more.

update: fixed a couple of typos

Replies are listed 'Best First'.
Re^4: sorting an array with mixed elements...
by blazar (Canon) on Jun 10, 2007 at 21:38 UTC
    You can't split it up completely,

    Just a tiny bit more, mixing your "solution" with lidden's:

    sub compare { my @A = split /:/, $a; my @B = split /:/, $b; $A[0] <=> $B[0]; } my @sorted = sort compare @table; print @sorted;

    (Incidentally I also changed the first argument to split, since it must be a pattern - strings are automatically converted of course, but there's one special case, so...)

    If it ain't clear like this... I don't know what could ever be!!