in reply to comparison with bitwise operators

I can think of 3 ways:
use warnings; use strict; use List::MoreUtils qw (any); my $var = 3; if (grep { $var == $_ } 2, 3) { print "in list\n"; } else { print "not in list\n"; } if (any { $var == $_ } 2, 3) { print "in list\n"; } else { print "not in list\n"; } my %vals = map {$_ => 1} 2, 3; if (exists $vals{$var}) { print "in list\n"; } else { print "not in list\n"; } __END__ in list in list in list
Update: a 4th way involves the smart match operator
use 5.010; if ($var ~~ [2, 3]) { print "in list\n"; } else { print "not in list\n"; }

Replies are listed 'Best First'.
Re^2: comparison with bitwise operators
by LanX (Saint) on Jan 13, 2011 at 22:23 UTC
    > my %vals = map {$_ => 1} 2, 3;
    > if (exists $vals{$var}) {
    >     print "in list\n";
    > }

    if you wanna test with exists hash-slices are shorter! :)

    my %vals; @vals{2,3}=();

    but need a separate step for declaration! :(

    UPDATE: why do you check with exists anyway?

    Cheers Rolf

      why do you check with exists anyway?
      Out of habit. I consider it defensive programming. In this small example, there is no need to use exists because I have clearly set the values of all keys to 1, which is defined and true, as opposed to undef or 0.

      I also kinda like how it reads.

      If you can convince me there is a significant penalty (performance/memory/etc.) for using exists, then I may consider changing my habit.

Re^2: comparison with bitwise operators
by alextor (Novice) on Jan 13, 2011 at 22:00 UTC
    thanks!