cosmicsoup has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

For many of you, this will be pretty simple, yet I'm having some problems putting this into code. I'm reading in a file.
open(IN, "<$file") || die "Can't open $file!\n"; while(<IN>) { chomp($_); my ($id, $stdate, $enddate, $person) = split(/\|\|/, $_); }
There is a many to many relationship between $id and $person. I want to produce a list that has a count of id's for each person. It seems a hash would be the most likely way to do this. But I haven't been able to get it to work. Here is what I would like to produce for the output:
James P 24 id's Alex S 50 id's Diane G 4 id's James A 12 id's Sam D 11 id's
Any thoughts?

Louis

Replies are listed 'Best First'.
Re: Simple perl counter
by Abigail-II (Bishop) on Apr 21, 2004 at 13:52 UTC
    $ perl -aF'\|\|' -nle '$F {$F [3]} ++; END {printf "%s has %d id\x27s\n" => $_, $F {$_} for keys %F}' data

    Abigail

Re: Simple perl counter
by matija (Priest) on Apr 21, 2004 at 13:18 UTC
    Well, what have you tried? Counting the ids in the loop can be done with $ids{$person}++; and you can output the list with
    foreach (keys %ids) { print "$_ $ids{$_} id\'s\n"; }
    Which of these two were you having trouble with?
Re: Simple perl counter
by Limbic~Region (Chancellor) on Apr 21, 2004 at 13:15 UTC
    Louis,
    You will have to forgive me if this is wrong - my brain has been missing for the last couple of weeks (Philippines) and I just found it (back to work).
    #!/usr/bin/perl use strict; use warnings; my $file = $ARGV[0] || 'input.txt'; open (INPUT, '<', $file) or die "Unable to open $file for reading : $! +"; my %data; while ( <INPUT> ) { chomp; my @info = split /\|\|/; push @{$data{$info[3]}}, $info[1] if ! $data{$info[3]} || ! grep / +^$info[1]$/ , @{$data{$info[3]}}; } for my $id ( keys %data ) { print "$id : " , scalar @{$data{$id}}, "\n"; }
    It assumes you only want unique ids counted - it is much easier if that is not the case : $data{$name}++

    Cheers - L~R