in reply to Re: Sorting an array of strings when some of the strings have commas in them?
in thread Sorting an array of strings when some of the strings have commas in them?

Sorry, I can't provide the full data due to that pesky confidentiality stuff, and I know that's not very helpful. Hopefully this will be just as good. Here is the same code tweaked a little to be more stand alone.

#!/usr/bin/perl use utf8; use 5.022; use strict; # Open the file for input, discard all the header lines, but stop on a +nd save the column names in an array. # Then read all the remaining lines in to an array and close the file. my $filename = "test.txt"; my $fh; open($fh, "<", $filename) or die "Cannot open \"$filename\" for input: + $!\n"; my $column_line = ""; $column_line = <$fh> while !($column_line =~ /Invoice ID/i); chomp(my @columns = split /\t/, $column_line); chomp(my @data_lines = <$fh>); close $fh; # Sort the data lines according to the "Company Name" field, and then +the "Invoice ID" field. my ($company_name_index) = grep { $columns[$_] eq "Company Name" } (0. +.$#columns); my ($invoice_ID_index) = grep { $columns[$_] eq "Invoice ID" } (0..$#c +olumns); @data_lines = sort { my($company_name_a, $invoice_ID_a) = (split /\t/, $a)[$company_nam +e_index, $invoice_ID_index]; my($company_name_b, $invoice_ID_b) = (split /\t/, $b)[$company_nam +e_index, $invoice_ID_index]; fc($company_name_a) cmp fc($company_name_b) or $invoice_ID_a <=> $invoice_ID_b } @data_lines; # Open the file for output, print the standard header to it, print the + now sorted data to it, then close the file. open($fh, ">", $filename) or die "Cannot open \"$filename\" for output +: $!\n"; print $fh "Replacement Header Text Here\n\n$column_line"; print $fh "$_\n" foreach @data_lines;

And when I run that with the exact original contents of the "test.txt" file as follows:

Original Header Text Invoice ID Company Name 1 SEBASTIAN COMMUNICATIONS 2 MASQUE SOUND 3 SEALEVEL SYSTEMS 4 MASSTECH, INC 5 SE INTERNATIONAL 6 SOUTHEAST SERVO, LLC 7 SEALEVEL SYSTEMS, INC. 8 MASTERBILT

Then the resulting modified "test.txt" file is:

Replacement Header Text Here Invoice ID Company Name 4 MASSTECH, INC 7 SEALEVEL SYSTEMS, INC. 6 SOUTHEAST SERVO, LLC 2 MASQUE SOUND 8 MASTERBILT 5 SE INTERNATIONAL 3 SEALEVEL SYSTEMS 1 SEBASTIAN COMMUNICATIONS

Does that help? Or rather, help you help me?

Replies are listed 'Best First'.
Re^3: Sorting an array of strings when some of the strings have commas in them?
by choroba (Cardinal) on Dec 11, 2015 at 22:53 UTC
    No, it doesn't help. It still sorts correctly: My guess: the indices are wrong. Your code sorts the file by a different column.
    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,