Test For Dupplicate elements in an array
I need to test if an array holds duplicates, and if so do something. What is the slickest way of doing this ? Neill __ Broadband from an unbeatable £15.99! http://www.tiscali.co.uk/products/broadband/home.html?code=SM-NL-11AM -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
RE: Test For Dupplicate elements in an array
[EMAIL PROTECTED] asked: I need to test if an array holds duplicates, and if so do something. Try use strict; use warnings; my @array = qw(foo baz bar foo); my %have; foreach my $item (@array){ warn duplicate item $item if exists $have{$item}; $have{$item}++; } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Test For Dupplicate elements in an array
On Apr 20, [EMAIL PROTECTED] said: I need to test if an array holds duplicates, and if so do something. What is the slickest way of doing this ? The documentation offers a couple ways; the most common idiom uses a hash, as other people have shown. However, you can leave the hard work to Perl if you use the Tie::Array::Unique module, available on CPAN: http://search.cpan.org/~pinyan/Tie-Array-Unique-0.01/ Basically, if you do: use Tie::Array::Unique; tie my(@data), 'Tie::Array::Unique'; and then use @data normally, it will make sure you don't duplicate any elements. -- Jeff japhy Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ CPAN ID: PINYAN[Need a programmer? If you like my work, let me know.] stu what does y/// stand for? tenderpuss why, yansliterate of course. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
RE: Test For Dupplicate elements in an array
[EMAIL PROTECTED] wrote: I need to test if an array holds duplicates, and if so do something. If you just need to check for the presence of a duplicate, something like this will do the trick: sub has_dup { my %seen; $seen{$_}++ return 1 for @_; } Of course, all the hash-based methods depend on uniqueness being determined by the stringified version of the array elements. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response