in reply to how do I sort numerically on sections of data that is alphanumeric

I don't think map or external modules are apt for a newbie!

Sorts can be placed in sub-routines to make your code simpler to read.

$a and $b are special sort vars. Read this for more info. <=> compares strings numerically. If they are the same, it returns '0'.

|| (or) only goes to the second comparison if the first is zero.

So, if you're sure the data is consistant:

my @sorted_array = sort { sort_me(); } @array; sub sort_me { # get 2nd and 3rd nums my ($a_2,$a_3) = ($a =~ /A (\d+) A(\d+)/); my ($b_2,$b_3) = ($b =~ /A (\d+) A(\d+)/); # sort by second nums. If same, sort by 3rd $a_2 <=> $b_2 || $a_3 <=> $b_3; }

cLive ;-)

  • Comment on Re: how do I sort numerically on sections of data that is alphanumeric
  • Download Code

Replies are listed 'Best First'.
Re: Re: how do I sort numerically on sections of data that is alphanumeric
by bikeNomad (Priest) on Jun 27, 2001 at 00:55 UTC
    Even more appropriate for a newbie (because it's less complex and doesn't use regexes) might be:

    my @sorted_array = sort { # compare the second numbers substr($a, 12, 9) <=> substr($b, 12, 9) # compare the third numbers or substr($a, 22, 12) <=> substr($b, 22, 12) } @array;

    That is, for each pair of lines that's being compared, use substr to get the fixed fields, and compare them numerically. The first <=> will return non-0 if the numbers in the second field are different, and the third field won't be compared in that case (because of the or).