Advertisement
cwchen

Sort data by id

Jan 13th, 2017
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.87 KB | None | 0 0
  1. use strict;
  2. use warnings;
  3. use autodie qw(open close);
  4.  
  5. # Replace data.txt with your file name.
  6. my $file = 'data.txt';
  7.  
  8. open my $FH, '<', $file;
  9.  
  10. my $index = 0;
  11. my @data; # Array to store data
  12. my @indices; # Array to store indices
  13. while (my $row = <$FH>) {
  14.     chomp $row;
  15.     if ($row =~ /(\d+\s*:\s*\d+\s*:\s*\d+\.\d+)\.(\d+)/) {
  16.         # Put data into the two arrays
  17.         push @data, $row;
  18.         push @indices, [$2, $index];
  19.     }
  20.     $index++;
  21. }
  22. close $FH;
  23.  
  24. # Sort indices by id
  25. my @indices_sorted = map { $_->[1] } sort { $a->[0] <=> $b->[0] } @indices;
  26. while (@indices_sorted) {
  27.     # Here we assume the data are always paired.
  28.     # You may need to deal with the issue.
  29.     my $i = shift @indices_sorted;
  30.     my $j = shift @indices_sorted;
  31.  
  32.     # You may use the two indices to access @data
  33.     # and do more.
  34.     print $i, ", ", $j, "\n";
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement