Re: Grep uniqueness issue
- From: japhy@xxxxxxxxxxxx (Jeff 'japhy' Pinyan)
- Date: Fri, 29 Jul 2005 11:32:15 -0400 (EDT)
On Jul 29, jason_normandin@xxxxxxxxxxx said:
I am having an odd problem using grep to ensure an array only contains distinct entries.
You should probably use a hash (along with your array, if you need to keep the order they're in) to ensure unique-ness.
support01-FastEthernet1/0 support01-RH jnormandin-p370-1691-SH-Cpu-2 jnormandin-p370-1691-SH
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));
There's NO reason to use a regex here at all. You don't want $element to be treated like a regex (since it's just a string). If you were gonna use grep(), you should just do
push @pingErrorsName, $element if !grep $_ eq $element, @pingErrorsName;
But I suggest you use a hash:
push @pingErrorsName, $element if !$uniq{$element}++;Read 'perldoc -q uniq' for more information.
* Where $element contains one of the above names in the list and @pingErrorsName is the distinct list of elements.
What I am finding is that the array will contain all of the correct entries except: jnormandin-p370-1691-SH. It appears as though the grep is matching jnormandin-p370-1691-SH to the jnormandin-p370-1691-SH-Cpu-2 string (as it is a substring of the second one).
Well, YES. That's because \b matches word boundaries. Between the 'H' and the '-' is a word boundary.
-- Jeff "japhy" Pinyan % How can we ever be the sold short or RPI Acacia Brother #734 % the cheated, we who for every service http://japhy.perlmonk.org/ % have long ago been overpaid? http://www.perlmonks.org/ % -- Meister Eckhart .
- References:
- Grep uniqueness issue
- From: Jason Normandin
- Grep uniqueness issue
- Prev by Date: Re: Re: Grep uniqueness issue
- Next by Date: Re: Re: Grep uniqueness issue
- Previous by thread: Re: Grep uniqueness issue
- Next by thread: Re: Re: Grep uniqueness issue
- Index(es):
Relevant Pages
|
|