in reply to Hashes with Multiple Keys and Combining Them
use strict; use warnings; my %AB; while (<DATA>) { chomp; my ($id, $name, $desc, $app) = split /\s*,\s*/; $AB{$id}{app} .= ",$app"; $AB{$id}{name_desc} = "$name, $desc"; } for (keys %AB) { $AB{$_}{app} =~ s/^,// } # remove leading comma for my $id (sort keys %AB) { print "$id, $AB{$id}{name_desc}, $AB{$id}{app} \n"; } __DATA__ 1, XYZ, desc, PDF 1, XYZ, desc, QFZ 2, YGH, desc, LMN
Update: On second thought, this version is cleaner because it does not unnecessarily inject that comma:
my %AB; while (<DATA>) { chomp; my ($id, $name, $desc, $app) = split /\s*,\s*/; push @{$AB{$id}{app}}, $app; $AB{$id}{name_desc} = "$name, $desc"; } for my $id (sort keys %AB) { print "$id, $AB{$id}{name_desc}, ", join(',', @{$AB{$id}{app}}), " +\n"; }
This prints:
1, XYZ, desc, PDF,QFZ 2, YGH, desc, LMN
I do know what I've been told about using the "my" before the various scalars, arrays, hashes, etc. The person that I'm writting these for doesn't like when I use those.Sorry, but my solution uses my and use strict. I refuse to code without them. If this person is your boss, look for another job; if this person is your spouse, get a divorce; otherwise, tell this person to become an educated Perl programmer :) (see Use strict and warnings)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Hashes with Multiple Keys and Combining Them
by de2425 (Sexton) on Sep 10, 2008 at 19:55 UTC |