Just to throw in one more way to do it with a sub:

###  MAIN  #########################

my $name = "Tim";
my @names = qw(Peter Paul Mary);
if( MatchAny($name,\@names) ){
  print "It's in there!\n";
}else{
  print "Go fish.\n";
}

###  SUBS  #########################

sub MatchAny{
  my( $search,$arRef ) = @_;
  #item to search for, array reference
  foreach( @{$arRef} ){ #or grep if you like
    return 1 if $search eq $_; 
    #makes the sub true
  }
  return 0;
  #if we didn't find it, it's false
}

The only reason why I sometimes prefer this approach is that it lets me keep
the main section of code fairly clean by separating out the searches and
checks into a separate subroutine.  That way I can get a better idea of the
flow of execution of the program without having to read every detail.  Also,
if I screw up the search algorithm, it's easier to tell what happened if you
know you made the mistake somewhere in the sub.

-----Original Message-----
From: Tara Calishain [mailto:[EMAIL PROTECTED]]
Sent: Sunday, July 28, 2002 2:28 PM
To: [EMAIL PROTECTED]
Subject: comparing to everything in an array?


Gentle Perl people,

Sorry to bother you with this, but I can't find the answer in my Pile of 
Perl Books.
I probably don't know enough to ask the question correctly.

I know you can compare two variables:

if ($foo eq $otherfoo) {things happen}

What I want to know is if you can do something that compares a variable to 
every element
in an array. For example, would something like

if ($foo eq @fooarray) {things happen}

work?

I'm trying to say, "If the variable $foo equals any element in the array 
@fooarray things
happen."

Thanks,

Tara
[EMAIL PROTECTED]  


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to