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

Daniel V. Ebert debert at dusya.osd.com
Tue Jan 11 12:55:36 CST 2000


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





More information about the spug-list mailing list