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{$_} }; } }
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

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

    "The grepping is slowing you down unnecessarily"

    By the way, it's also plain weird. If you want to check for the existence of hash keys, then there's the exists keyword:

    if (exists $count{$ipb} and exists $count{$ipb}{$ipa})
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re^2: How to merge data in IP address pairs
by -=Markus=- (Initiate) on May 27, 2012 at 14:54 UTC
    Hi Tobyink,

    Thank you a million - works like a charm! You totally saved my week! :)

    Kind regards,

    -=Markus=-