Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

One liner to check if variable matches any of an array's elements 5

Status
Not open for further replies.

mikawin

Technical User
Apr 15, 2009
28
US
Hi,

Is there a one-liner code that will check to see if a particular variable's value (for e.g $myVar = "S") matches any of the elements of a pre-defined array(
@myArray = (P Q R S)?

Thanks,
Mika
 
Take a look at the grep function

Code:
if (grep {$myVar} @myArray) {
  # At Least 1 Match - do stuff
} else {
  # No Match - do other stuff
}
 
Slight enhancement to rharsh's code for completeness:

Code:
[olive][b]if[/b][/olive] [red]([/red][url=http://perldoc.perl.org/functions/grep.html][black][b]grep[/b][/black][/url] [red]{[/red][blue]$myVar[/blue] eq [blue]$_[/blue][red]}[/red] [blue]@myArray[/blue][red])[/red] [red]{[/red]
  [gray][i]# At Least 1 Match - do stuff[/i][/gray]
[red]}[/red] [olive][b]else[/b][/olive] [red]{[/red]
  [gray][i]# No Match - do other stuff[/i][/gray]
[red]}[/red]
 
Hi

If you can ignore backward compatibility, Perl 5.10 smart matching operator [tt]~~[/tt] can do this :
Code:
[blue]  DB<1>[/blue] @myArray = qw(P Q R S)

[blue]  DB<2>[/blue] $myVar = "S"

[blue]  DB<3>[/blue] print $myVar~~@myArray
1

[blue]  DB<4>[/blue] $myVar = "F"

[blue]  DB<5>[/blue] print $myVar~~@myArray


Feherke.
 
I agree, thanks Feherke. I'm not sure how needed that operator truly is, but it's nice to know about it all the same. Star from me as well.

- MillerH
 
@MillerH - it short circuits.
perlsyn said:
Note that the "Matching Code" column is not always an exact rendition. For example, the smart match operator short-circuits whenever possible, but grep does not.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top