Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I'm sure there is a real simple structure for this. I have an if condition with several different solutions. (red or green or blue or yellow or black or brown)I would like to avoid having to type "if (@bands[0] eq 'red' || @bands[0] eq 'green' || etc......" I have scoured google but its either too specific of a question or my terminology isn't appropriate. How can I shorten it to be something like "if @bands[0] is one of either red, green, blue, yellow, etc...."

Replies are listed 'Best First'.
Re: If condition operator
by toolic (Bishop) on Aug 30, 2011 at 18:03 UTC
    A few other approaches...

    grep

    if (grep { $bands[0] eq $_ } qw(red green blue yellow))

    List::MoreUtils

    use List::MoreUtils qw(any); if (any { $bands[0] eq $_ } qw(red green blue yellow))

    Hash, map, exists

    my %colors = map { $_ => 1 } qw(red green blue yellow); if (exists $colors{$bands[0]})
Re: If condition operator
by hbm (Hermit) on Aug 30, 2011 at 18:21 UTC

    Could use a regular expression: if $bands[0]=~/^(?:red|green|blue|yellow)$/

Re: If condition operator
by ww (Archbishop) on Aug 30, 2011 at 18:10 UTC
    #!usr/bin/perl use warnings; use strict; use 5.012; # 923276 my @bands = qw(red green blue yellow black brown); my $test = "green"; for my $band(@bands) { if ($test eq $band) { say "matched $test and $band"; } }

    Output: matched green and green

Re: If condition operator
by AnomalousMonk (Archbishop) on Aug 31, 2011 at 00:22 UTC

    Isn't this what smart matching is for (if you have 5.10+)?

    >perl -wMstrict -lE "my @colors = qw(red green blue yellow); my @bands = qw(green pink); ;; say qq{$bands[0] matches} if $bands[0] ~~ @colors; say qq{$bands[1] matches} if $bands[1] ~~ @colors; " green matches