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

here is a tricky question (for me anyway). I'm parsing data and storing duplicate names in a hash like so:
my %seen = (); while (<DATA>) { if ($seen{$name}++) { push @names, $name; } }
My problem is in the comparison within the hash. I seem to loose the very first duplicate name. I understand why, but am unclear with a solution
Is there an easy fix for this?

Replies are listed 'Best First'.
Re: capturing duplicates
by tilly (Archbishop) on Jun 27, 2003 at 19:03 UTC
    Just have two passes. One to get the counts, one to filter.
    chomp(my @names = <DATA>); my %seen; foreach (@names) { $seen{$_}++; } @names = grep {1 < $seen{$_}} @names;
Re: capturing duplicates
by Zed_Lopez (Chaplain) on Jun 27, 2003 at 22:01 UTC

    Your code as written could use

    chomp; my $name = $_;

    after the

    while (<DATA>) {

    (or just use $_ instead of $name.) With that, it works as you want. Without that it does nothing. So you probably made an error when you cut and pasted your code.

    If you've still got questions, could you post the code as you're running it, and the data with which it's failing?