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

I have a program that has the user enter in a bunch of values making a list. What I need the program then to find out, is if the user has entered in the same value more than once. And if the User has entered in the value more than once I need to have the program display what the value is that has been entered in more than once.

Replies are listed 'Best First'.
Re: Simple Array
by swiftone (Curate) on Sep 11, 2000 at 22:54 UTC
    This is best done with a hash during user entry. See How do I use a hash as a set? for more details, but basically:
    while(<STDIN>){ push @array, $_; if($hash{$_}){ print "$_ was entered more than once\n"; } $hash{$_}++; }
    If your hash is declared as a my() variable inside a block during entry, you can even have the memory freed when you leave the block.
(Ovid) Re: Simple Array
by Ovid (Cardinal) on Sep 11, 2000 at 23:07 UTC
    I would use something similar to what swiftone has written, but I would populate the hash directly and skip the array:
    while (<STDIN>) { $some_hash{$_}++; }
    The value of each key is the numer of entries in the list. If you need to iterate over the list, you use something like this:
    foreach (keys %some_hash) { ...some code here... }
    If you maintain a seperate list and hash, you have to update both if one changes. With this method, you only need to track one and thus have an easier maintenance job. The drawback is you lose ordering on the list, but since we have user entered data, this ordering may not matter. If necessary, you could try to keep order with the following (untested) code:
    my $position = 1; while (<STDIN>) { $myhash{$_}{'item'}++; $myhash{$_}{'position'} = $position++ if ! exists $myhash{$_}{'pos +ition'}; }

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just go the the link and check out our stats.

      i use code like this all the time. but be careful - you may get results that shouldn't be duplicate ( like smith and Smith, which in your context may be the same.)

      depending on your usage, some preprocessing may be in order.

Re: Simple Array
by runrig (Abbot) on Sep 12, 2000 at 00:07 UTC
    What kind of values? Numeric? Then should '3', '3.0' and '3.00' be considered 'the same'?

    If so, then use sprintf to create stringified fixed decimal numbers before storing them in a hash, or int() if they should be integers anyway.