Ankur Gupta wrote:
[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]> wrote:

Hey Guys

I am having an odd problem using grep to ensure an array only
contains distinct entries.
I have a list similar to the following in a file (short example of a
much longer list)
support01-FastEthernet1/0
support01-RH
jnormandin-p370-1691-SH-Cpu-2
jnormandin-p370-1691-SH

These entries may or may not appear multiple times within that list.

I am trying to create an ARRAY containing each of these entries only
once (a distinct list). I am using a grep statement:
push @pingErrorsName, $element if (! grep (/\b$element\b/,
@pingErrorsName));


push @pingErrorsName, $element if ( ! grep { $_ eq $element }
@pingErrorsName );

or
push @pingErrorsName, $element if ( ! grep { /^$element$/ }
@pingErrorsName );

should work.. (untested though).

But this would be inefficient for large arrays.

Use hash instead.

$pingErrorsName{$element} = undef;

Retrieve the elements by
@elements = (keys %pingErrorsName);



This loses the sort order, if you care.


foreach $element....
{
        next if exists $hash{$element};
        --OR--
        next if grep( /$element/, @array);
        push @array, $element;
        $hash{element} = 1;
}
undef %hash;  # house cleaning

I suspect that the grep approach slows down with larger arrays while the %hash approach is a memory hog... This is also one of those times where the use of 'o' in your regex /$element/o would be VERY VERY bad... :)

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to