http://www.perlmonks.org?node_id=626681


in reply to Counting the Times Two Unknown Values Appear Together

I think maybe you want this:

while (<FILE>){ my ($src,$sport) = (split /;/)[9,12]; $hash{$src}{$sport}++; }

Then you can say something like...

foreach my $src ( keys %hash ) { foreach my $sport ( keys %{$hash{$src}} ) { printf "%s appears with %s %d times\n", $src, $sport, $hash{$src}{$sport}; } }

Or just use something like Data::Dumper or YAML to spew out the whole structure.

Replies are listed 'Best First'.
Re^2: Counting the Times Two Unknown Values Appear Together
by jdporter (Canon) on Jul 16, 2007 at 02:36 UTC

    I'd simplify it a bit further:

    my %count; while (<FILE>) { my( $src, $sport ) = (split /;/)[9,12]; $count{$src,$sport}++; # magic $; } for my $pair ( sort keys %count ) { print "($pair) occurred on a line together $count{$pair} times\n"; # if you need the two parts: # my( $src, $sport ) = split $;, $pair; }
    In fact, I'd extend it to any number of fields:
    my @fields = ( 9, 12 ); my %count; while (<FILE>) { chomp; $count{ (split /;/)[@fields] }++; } for ( sort keys %count ) { print "($_) occurred on a line together $count{$_} times\n"; # if you need the parts: # my @vec = split $;; }
Re^2: Counting the Times Two Unknown Values Appear Together
by Dru (Hermit) on Jul 16, 2007 at 13:53 UTC
    Cool, this is what I went with and it does exactly what I want, thanks!

    P.S. I looked at your home node and saw "Other monks I've met in person:" line and when I first read it, I thought it said "Other monks I've met in prison!!"

    P.P.S. Thanks to the other monks for their responses as well.

    Thanks,
    Dru

    Perl, the Leatherman of Programming languages. - qazwart