user2795662
user2795662

Reputation: 33

Sort a Single Column in Ascending or Descending Order using Perl

I am trying to sort the following price columns within a text file using Perl.

Time    Num    Size     Price Act | Act Price   Size    Num       Time  
11:30:12.957    1   3000 11.90  A  |  A  11.05   500     1      11:30:12.954   
11:30:12.957    1   100  11.75  A  |  A  14.00   1676    3      11:30:12.957

I can read the text file into an array and sort it fine by row but I cannot think of how to sort a specific column in Ascending or Descending order? Tried reading in the text file one element at a time as follows to start with and then attempting to sort the first Price Column in descending order

use strict;
use warnings;

open(my $file_handle, '<', 'Data.txt') or die("Error: File cannot be opend:  $!");

my @words;

while (<$file_handle>) {
chomp;
@words = split(' ');
}

Upvotes: 1

Views: 1243

Answers (1)

mpapec
mpapec

Reputation: 50637

use strict;
use warnings;

open(my $file_handle, '<', 'Data.txt') or die("Error: File cannot be opend:  $!");

my @rows;

while (<$file_handle>) {
  $. > 1 or next; # skip header line
  chomp;
  push @rows, [ split ]; # split current line on \s+ 
}

# sort descending on 4-th column
@rows = sort { $b->[3] <=> $a->[3] } @rows;

# ascending sort on same column
# @rows = sort { $a->[3] <=> $b->[3] } @rows;

Upvotes: 2

Related Questions