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

I have the following array:
001928: 12:33:01,active,,1234,847 001928: 12:33:02,hold,,4321,847 001928: 12:33:03,transfer,,2341,847 001928: 12:32:59,ring,,1234,847 001928: 12:33:00,answer,,1234,847
I want to sort this based on the time, 12:32:59 to 12:33:03, but keeping the lines in place. So the result looks like this:
001928: 12:32:59,ring,,1234,847 001928: 12:33:00,answer,,1234,847 001928: 12:33:01,active,,1234,847 001928: 12:33:02,hold,,4321,847 001928: 12:33:03,transfer,,2341,847

Replies are listed 'Best First'.
Re: How do you sort an array?
by tadman (Prior) on Mar 22, 2001 at 23:56 UTC
    You should write a custom sort routine which will work with your data, and you do this by using the optional sort() function parameter. This can enable sort() to order your data not by the value of the data itself, but by some calculated value derived from it.
    sub by_time { # $a and $b are things to be compared from sort() # Convert $a and $b into integer values # Extract the time from the string into $a_v my ($a_v) = $a =~ / (\d\d?:\d\d:\d\d)/; # Remove colons to create a numeric-only value $a_v =~ tr/://d; # Same for $b my ($b_v) = $b =~ / (\d\d?:\d\d:\d\d)/; $b_v =~ tr/://d; # Return the difference (0 = same) return $a - $b; } foreach (sort by_time @stuff) { print "$_\n"; }
      Thanks!
Re: How do you sort an array?
by InfiniteSilence (Curate) on Mar 23, 2001 at 01:37 UTC
    I ran the first listing's code and it failed to sort the array. Here's the fix:
    15 16 # Return the difference (0 = same) 17 return $a_v - $b_v; 18 } 19
    was originally :
    15 16 # Return the difference (0 = same) 17 return $a - $b; 18 } 19

    Celebrate Intellectual Diversity

      Thank you so much for taking the time. :)
Re: How do you sort an array?
by Ido (Hermit) on Mar 23, 2001 at 01:56 UTC
    @sortedarray=map $_->{orig},sort {$a->{h}<=>$b->{h} and $a->{m}<=>$b-> +{m} and $a->{s}<=>$b->{s}} map {my($h,$m,$s)=/: (\d{2}):(\d{2}):(\d{2 +} +)/;{h=>$h,m=>$m,s=>$s,orig=>$_}} @array;