in reply to How to merge data in IP address pairs
The grepping is slowing you down unnecessarily. Just use sort to make sure that you always refer to the IP addresses in a predictable order.
my $filename = shift @ARGV; die "Usage: $0 FILENAME" unless defined $filename; open my $fh, '<', $ARGV[0] or die "Could not open file '$filename': $!"; my %count; INPUT: while (<$fh>) { chomp; my ($ip1, $ip2, $bytes) = split /\s+/; ($ip1, $ip2) = sort ($ip1, $ip2); $count{$ip1, $ip2} += $bytes; } OUTPUT: { local $, = "\t"; local $\ = "\n"; foreach (keys %count) { my ($ip1, $ip2) = split $;, $_; print $ip1, $ip2, $count{$_}; } }
Adding extra columns is not much different.
my $filename = shift @ARGV; die "Usage: $0 FILENAME" unless defined $filename; open my $fh, '<', $ARGV[0] or die "Could not open file '$filename': $!"; my %count; INPUT: while (<$fh>) { chomp; my ($ip1, $ip2, @data) = split /\s+/; ($ip1, $ip2) = sort ($ip1, $ip2); $count{$ip1, $ip2}[$_] += $data[$_] for 0 .. $#data; } OUTPUT: { local $, = "\t"; local $\ = "\n"; foreach (keys %count) { my ($ip1, $ip2) = split $;, $_; print $ip1, $ip2, @{ $count{$_} }; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to merge data in IP address pairs
by tobyink (Canon) on May 27, 2012 at 14:37 UTC | |
|
Re^2: How to merge data in IP address pairs
by -=Markus=- (Initiate) on May 27, 2012 at 14:54 UTC |