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

Joel largest at largest.org
Tue Jan 11 13:44:19 CST 2000


Daniel Ebert wrote: 

> The object of the code is to remove from @array1 those elements which
> are in @array2 > @targetArrray.

Hi Dan,

See the Perl Cookbook, recipe 4.7 for something very similar to this:

#---------------------------------------------------------------
my %seen;
my @targetArray;

# build lookup table
@seen{@array2} = ();

foreach $item ( @array1 ) {
    push ( @targetArray, $item ) unless exists $seen{$item};
}
#---------------------------------------------------------------


Joel



> 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
> 
> 
> 
> 

---------------------------------------------------
Procedure Computers_Move(var CPU_Turn :boolean);
var a:integer;
begin
  writeln('Computer decides to skip this round. ');
  CPU_Turn := False;
end;


 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    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