SPUG: Array comparison and "breaking" out of a foreach loop

Rick Croote rcroot at atl.com
Tue Jan 11 16:46:01 CST 2000


(BTW, sorry if you get this twice, I suffered through a crash and cannot
find any evidence that the first instance was actually sent.)
Assuming that there are no duplicates in any given array, as your example
eludes to, then I would use the hash array to count the occurances, and then
look for those that only occured once.

#
# Count all occurances, incrementing by one for each
# one found.
#
my %found;
foreach (@array1, @array2)
{
    $found{$_}++;
}

#
# Now retrieve those elements in array1 that did not
# exist in array2.
#
my @targetArray = grep $found{$_} == 1, @array1;

---

Rick Croote
ATL Ultrasound

----- Original Message -----
From: Daniel V. Ebert <debert at dusya.osd.com>
To: <spug-list at pm.org>
Sent: Tuesday, January 11, 2000 10:55 AM
Subject: SPUG: Array comparison and "breaking" out of a foreach loop


>
> Does this code do what I think it does?
>
> The object of the code is to remove from @array1 those elements which are
in
> @array2 > @targetArrray.
>
> In "real life" the lengths of @array1 and @array2 are variable, but
@array1
> will always be larger than @array2.
>
> If there is a more efficent way of comparing two arrays of strings I'm all
> ears.  Thanks!
>
> #!/usr/bin/perl -w
>
> @array1 = ("a","b","c","d","e","f","g"); #create @array1
> @array2 = ("a","b","e","g"); #create @array2
>
> # Here's what I want to create:  @targetArray should be ("c","d","f")
>
>
> OUTER: foreach $entry1 (@array1) { #cycle thru elements of @array1
> $check = 0; #(re)set flag to 0
> INNER: foreach $entry2 (@array2) { #cycle thru elements of @array2
>   if ($entry1 eq $entry2) {$check = 1; last INNER} #if
> condition met set flag then stop testing $entry1
> }
> if ($check != 1) {push @targetArray, $entry1;} #add elem to new array
> }
>
> foreach $elem (@targetArray) {print $elem, "\n";} #print new array
>
>
>
> ---
> Dan Ebert
> Seanet Internet Services
> (206)343-7828
>
>  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
>     POST TO: spug-list at pm.org        PROBLEMS: owner-spug-list at pm.org
>  Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
>  SUBSCRIBE/UNSUBSCRIBE: Replace ACTION below by subscribe or unsubscribe
>         Email to majordomo at pm.org: ACTION spug-list your_address
>
>


 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    POST TO: spug-list at pm.org        PROBLEMS: owner-spug-list at pm.org
 Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
 SUBSCRIBE/UNSUBSCRIBE: Replace ACTION below by subscribe or unsubscribe
        Email to majordomo at pm.org: ACTION spug-list your_address





More information about the spug-list mailing list