http://qs321.pair.com?node_id=1094090


in reply to grep { $var } @arr

Yes you can do that but I usually do it like this:
@res = grep (/$pat/g, @arr);
Perl 5.8.8 on Redhat Linux RHEL 5.5.56 (64-bit)

Replies are listed 'Best First'.
Re^2: grep { $var } @arr
by Laurent_R (Canon) on Jul 17, 2014 at 18:55 UTC
    Well, bulrush, you did not say how you populate $pat, but I fail to see how a regex would figure out whether a value is larger or smaller than 3.

    I definitely agree that a subroutine reference is a very good solution, perhaps the best.

      I fail to see how a regex would figure out whether a value is larger or smaller than 3.

      You can get clever with match-time pattern interpolation. For instance:

      my @list = (1..5); my $pattern = qr/\d+(??{if($& < 3) { "" } else { "(?<!\\d)" } })/; my @res = grep /$pattern/, @list; say join ", ", @res;

      This also (ab)uses negative look-behind assertions to create a subpattern that is guaranteed to fail (in this regex, not in general).

      But I agree, subroutine references are the way to go here.

        Yeah, that's clever ++, that that expression is far from being regular.
Re^2: grep { $var } @arr
by igelkott (Priest) on Jul 21, 2014 at 07:10 UTC
    /$pat/g

    Perhaps I've misunderstood but with my current $var, using /$pat/g will result in no matches (with or without the 'g' modifier). As far as I know, this will look for the literal string of '$_ < 3' on my array, as written below (appending to the initial script).

    @res = grep {/$pat/g} @arr; print "Search:\t@res\n";

    This finds none of the elements of @arr.