Adding arrays?
Eric Schwartz
erics at cos.agilent.com
Thu Jul 26 10:49:01 CDT 2001
On Wed, Jul 25, 2001 at 07:40:21PM -0600, Don Johnson wrote:
> Robert -
>
> You solution will work fine. The only trouble you might run into is if
> you don't want to allow duplicate values in the resulting array. If
> @TempArray contains values already in @FinalArray, and you want to
> disallow duplicates, you could use the keys of a hash to ensure no
> duplicates:
>
> %hash = ();
> foreach $key (@FinalArray) {
> $hash{$key} = 1; # we've seen this key
> }
> foreach $key (@TempArray) {
> $hash{$key} = 1; # we've seen this key
> }
> @FinalArray = keys %hash;
This is a great chance to use the handy perl language feature 'map'. You
can do the exact same thing as this snippet above in two lines:
map { $hash{$_}++ } (@FinalArray, @TempArray);
@FinalArray = keys %hash;
'map' iterates over a list, and executes the associated code block once
for every item in the list, setting $_ to the item. I've found that when
I feel the need to write a simple iterator, 90% of the time it's much
clearer and easier to use 'map'.
'grep' is similar to map, but it returns a list of all the items for
which the function returned true. For instance, to extract all the items
from @FinalArray that begin with the letter 'a':
@onlyAs = grep { /^a/ } @FinalArray;
That's my Fun Perl Hint Of The Day(tm).
-=Eric
--
Man usually avoids attributing cleverness to somebody else -- unless it
is an enemy.
-- Albert Einstein
More information about the Pikes-peak-pm
mailing list