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

how do you use reqular expressions in arrays. say I want find out if $test begins with "foo" and/or ends with "bar" using an array?
$test =~ /^foo /; $test =~ / bar$/;
something like:
@compare = "/^foo /", "/ bar$/"; $i=0 foreach (@compare){ unless $test =~ @compare[$i]){ print $test; $i++ }

Replies are listed 'Best First'.
Re: Regular expressions and Arrays
by broquaint (Abbot) on Apr 26, 2004 at 16:59 UTC
    The usual approach is to use grep e.g
    do_something(@compare) if grep { $test =~ $_ } @compare;
    However the first function from List::Util is better suited for this situation e.g
    use List::Util 'first'; do_something(@compare) if first { $test =~ $_ } @compare;
    HTH

    _________
    broquaint

Re: Regular expressions and Arrays
by kvale (Monsignor) on Apr 26, 2004 at 17:01 UTC
    my @rx = (qr|^foo |, qr| bar$|); my $passed = 1; foreach my $rx (@rx) { $passed = 0 unless $test =~ /$rx/; } print $passed ? "Passed\n" : "Failed\n";

    -Mark

Re: Regular expressions and Arrays
by Enlil (Parson) on Apr 26, 2004 at 17:46 UTC
    Depending on the tests you might not need an array in lieu of alternation. And thus I present two other ways of solving your example:

    1.

    use strict; use warnings; while ( <DATA> ) { if ( /(^foo.*bar$)|(^foo)|(bar$)/ ){ print $1 ? "BOTH FOO AND BAR: $_" : $2 ? "ONLY FOO: $_" : "ONLY BAR: $_"; } else { print "NOT EITHER: $_" } } __DATA__ foo baz foo bar bar fu bar fuz foo on you bar
    2.
    use strict; use warnings; while ( <DATA> ) { /(^foo.*bar$)(?{print "BOTH FOUND: $_"}) | (^foo) (?{print "FOO FOUND: $_"}) | (bar$) (?{print "BAR FOUND: $_"})/x } __DATA__ foo baz foo bar bar fu bar fuz foo on you bar

    -enlil

Re: Regular expressions and Arrays
by bart (Canon) on Apr 26, 2004 at 19:23 UTC
    In Perl, the slashes are not part of the regular expression. So drop them and you're getting close to something you could use.
    @compare = ('^foo ', ' bar$'); $i=0; foreach (@compare){ unless $test =~ $compare[$i]){ print $test; $i++ } }
    But even though this will work, I agree with kvale: if at all possible, you'd be better of using qr//.
Re: Regular expressions and Arrays
by pizza_milkshake (Monk) on Apr 26, 2004 at 21:39 UTC
    pizza@pizzabox:~$ perl -le'$r = join "|", qw/ ^foo bar$ /; $rgx = qr{$ +r}; print int($_ =~ $rgx) . " $_" for qw/boo food bar barf foobar/' 0 boo 1 food 1 bar 0 barf 1 foobar

    perl -e'$_="nwdd\x7F^n\x7Flm{{llql0}qs\x14";s/./chr(ord$&^30)/ge;print'

Re: Regular expressions and Arrays
by ccn (Vicar) on Apr 26, 2004 at 16:59 UTC
    
    @compare = map{qr/$_/} qw'^foo bar$';
    
    print $test unless $test =~ /$_/ foreach @compare;