Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Perl help

by kcott (Archbishop)
on Sep 10, 2016 at 14:54 UTC ( [id://1171512]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1171512]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2024-04-16 09:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found