in reply to •Re: Reformat Text File
in thread Reformat Text File

This assumes that the keys are in sorted order to begin with and that it's easy to re-sort them. Instead, you might want to preserve the original order as much as possible.
my %result; my @keys; while (<>) { chomp; my ($k, $v) = split /,/; push @keys,$k if (!exists $result{$k}); push @{$result{$k}}, $v; } for (@keys) { print join(",", $_, @{$result{$_}}), "\n"; }

Replies are listed 'Best First'.
Re^3: Reformat Text File
by gaal (Parson) on Oct 05, 2004 at 16:37 UTC
    > This assumes that the keys are in sorted order

    What makes you say that?

      bah,valueA foo,valueB foo,valueC bar,valueD

      results in

      bah,valueA bar,valueD foo,valueB,valueC

      and not

      bah,valueA foo,valueB,valueC bar,valueD

      Therefore, merlyn assumes they are sorted (or assumes the order of the lines in the result doesn't matter, but then why call sort?).

      I presume the problem has been simplified from an original case with meaningful keys in some meaningful order. Say the keys were dates in some odd format:
      July 21,Milestone meeting August 3,First walkthrough August 3,Committee meeting September 12,Second walkthrough
      merlyn puts all the values into a hash and then does a straight sort on the keys. That would make "August 3" come before "July 21" in my example. Rather than work out a fancy sorting routine for dates (or whatever the keys might be), my example maintains the original order of the first appearance of each key.