Re: Stumped with a Posix/Perl Question
On Thu, Apr 01, 2004 at 02:10:46PM -0800, William Ballard wrote:
> Given:
>
> A - 1
> A - 2
> B - 1
> B - 2
>
> what's the simplest command or perl script to print it as:
>
> A (1, 2)
> B (1, 2)
>
> or something equivalent.
Hmm, one of the zillions of ways of doing something equivalent, with the
data in file tmp/msg-data:
$ perl -nae '{push @{$x{$F[0]}},$F[2]}END{foreach(sort keys %x){print "$_ ("; print join(", ",@{$x{$_}});print ")\n"}}' tmp/msg-data
A (1, 2)
B (1, 2)
or perhaps a bit more legibly:
#!/usr/bin/perl -w
use strict;
my %x;
while ( <DATA> ) {
chomp;
my @F = split;
push @{$x{$F[0]}}, $F[2]
}
foreach ( sort keys %x ) {
print "$_ (";
print join(", ",@{$x{$_}});
print ")\n"
}
__END__
A - 1
A - 2
B - 1
B - 2
This builds a hash keyed on the first space-delimited token on a line,
with the hash value being an array reference to which the 3rd token
is pushed. Afterwards the hash is iterated for printing, and the arrays
pretty-printed using join.
Ken
--
Ken Irving, Research Analyst, fnkci@uaf.edu, 907-474-6152
Water and Environmental Research Center
Institute of Northern Engineering
University of Alaska, Fairbanks
Reply to: