CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Comparing an array with another array

 



dude
New User

Dec 7, 2009, 7:37 AM

Post #1 of 3 (393 views)
Comparing an array with another array Can't Post

I apologize for such a simplistic question; however, I am new to programming with Perl.

I would like to compare multiple strings within an array to another array. For example if I have three arrays:

Code
@varlist = ('banana','spinach','apple'); 
@fruits = ('orange','apple','pear','banana');
@vegs = ('spinach','carrot','peas');


I would like to loop through the array varlist and compare each entry to the arrays fruits and vegs.

Perhaps it would look something like this:

Code
my @varlist = ('banana','spinach','apple'); 
my @fruits = ('orange','apple','pear','banana');
my @vegs = ('spinach','carrot','peas');

my $var_list_size = scalar @varlist;

for (my $i = 1; $i <= $var_list_size; $i++){

if (?????) {

print "$varlist[$i] is a fruit";

} elsif (??????) {

print "$varlist[$i} is a vegetable";

} else{

print "$varlist[$i} is neither vegetable nor fruit";
}
}

I'm not sure how to fill in the logical conditions in the if and elsif statements.

Thank you in advance for your help!!


toolic
User

Dec 7, 2009, 9:59 AM

Post #2 of 3 (369 views)
Re: [dude] Comparing an array with another array [In reply to] Can't Post

You could use Perl's grep function:


Code
use strict; 
use warnings;

my @varlist = ('banana','spinach','apple');
my @fruits = ('orangoue','apple','pear','banana');
my @vegs = ('spinach','carrot','peas');

for my $var (@varlist) {
if (grep { $var eq $_ } @fruits) {
print "$var is a fruit.\n";
}
elsif (grep { $var eq $_ } @vegs) {
print "$var is a vegetable.\n";
}
else {
print "$var is neither vegetable nor fruit.\n";
}
}

__END__
banana is a fruit.
spinach is a vegetable.
apple is a fruit.



toolic
User

Dec 7, 2009, 5:30 PM

Post #3 of 3 (346 views)
Re: [toolic] Comparing an array with another array [In reply to] Can't Post

Here is another solution using hashes, which have the potential for quicker look-ups:

Code
use strict; 
use warnings;

my @varlist = qw( banana spinach apple );
my %fruits = map { $_ => 1 } qw( orangoue apple pear banana );
my %vegs = map { $_ => 1 } qw( spinach carrot peas );
for my $var (@varlist) {
if ( exists $fruits{$var} ) {
print "$var is a fruit.\n";
}
elsif ( exists $vegs{$var} ) {
print "$var is a vegetable.\n";
}
else {
print "$var is neither vegetable nor fruit.\n";
}
}


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives