0

Possible Duplicate:
How can I check if a Perl array contains a particular value?

I have two arrays @array1 = (1..26);, @array2 = ('a'..'z'); and a variable $x. suppose $x=5 then how can I compare this value with two arrays and state in output that this variable belongs to @array1?

Community
  • 1
  • 1

3 Answers3

5

Perl 5.10 and greater has a new smart match operator that makes easy work of this task:

if ($x ~~ @array1) {
  say '$x is in @array1';
}
elsif ($x ~~ @array2) {
  say '$x is in @array2';
}
else {
  say '$x is not in either array.';
}
titanofold
  • 2,852
  • 1
  • 15
  • 21
3

You can use the smartmatch:

say   $x ~~ \@array1 ? 'first'
    : $x ~~ \@array2 ? 'second'
    : 'none';
choroba
  • 231,213
  • 25
  • 204
  • 289
2

If you want to avoid the controversial smart-match operator, you can use grep.

say   grep { $x eq $_ } @array1 ? "first"
    : grep { $x eq $_ } @array2 ? "second"
    : "none";

You should be using hashes here if you do this repeatedly.

my %array1 = map { $_ => 1 } @array1;
my %array2 = map { $_ => 1 } @array2;

say   $array1{$x} ? "first"
    : $array2{$x} ? "second"
    : "none";
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Note: `grep` will check every element instead of stopping asap, but that's rarely a concern. – ikegami Nov 01 '12 at 11:03
  • [List::MoreUtils](http://p3rl.org/List::MoreUtils)'s `any` function could replace `grep` here. But if efficiency is an issue, than clearly the hash version outperforms everything because hash lookups take constant time. – memowe Nov 01 '12 at 13:22