Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: grep { $var } @arr

by bulrush (Scribe)
on Jul 17, 2014 at 16:53 UTC ( #1094090=note: print w/replies, xml ) Need Help??

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

    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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1094090]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2021-04-15 17:14 GMT
Find Nodes?
    Voting Booth?

    No recent polls found