in reply to Perl help
G'day hello_beginner,
I think you have an overly complex data structure: a Hash of Hashes of Arrays (HoHoA). I've used a Hash of Arrays (HoA): the keys are col1 values (e.g. A1, A2, etc.); the values are arrayrefs containing all the elements returned by split.
[In the code below: UNIQ refers to your A1, A2 & A3; CODE refers to your NY, SG, AUS, etc. codes.]
#!/usr/bin/env perl -l use strict; use warnings; use autodie; use constant { UNIQ => 0, CODE => 2, JOINER => ':', }; my %data; while (<DATA>) { my @cols = split; if (exists $data{$cols[UNIQ]}) { $data{$cols[UNIQ]}->[CODE] .= JOINER . $cols[CODE]; } else { $data{$cols[UNIQ]} = [ @cols ]; } } print "@{$data{$_}}" for sort keys %data; __DATA__ A1 text1 NY Jan 01 A2 text2 LN Feb 02 A3 text3 SG Mar 03 A2 text2 NY Feb 02 A1 text1 SG Jan 01 A1 text1 AUS Jan 01
Which outputs:
A1 text1 NY:SG:AUS Jan 01 A2 text2 LN:NY Feb 02 A3 text3 SG Mar 03
See also: "perldsc -- Perl Data Structures Cookbook".
— Ken
|
|---|