Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^3: Regular expression help: why does this not match?

by gaal (Parson)
on Jan 19, 2007 at 07:40 UTC ( [id://595415]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Regular expression help: why does this not match?
in thread Regular expression help: why does this not match?

It may be surprising at first, but the idea is that it lets you construct regexps on the fly. One common thing this is used for is when you have a list of valid values you got from somewhere, say @valid, and you want to check a value against it:

my $valid = join "|", @valid; print "okay" if /^$valid$/;

There are actually two improvements to make in the above code. First, the members of the valid list themselves might contain metacharacters in need of quoting; second, Perl has the qr// operator to make this more efficient:

# don't run this code on every match: the idea is the qr// needs # to be computed only once. my $valid = join "|", map { quotemeta } @valid; my $valid_re = qr/^$valid$/; # now match as many times as you like. print "$_: " . (/$valid_re/ ? "okay" : "not okay") . "\n" for @a_bunch_of_inputs;

Replies are listed 'Best First'.
Re^4: Regular expression help: why does this not match?
by Hofmator (Curate) on Jan 19, 2007 at 08:01 UTC
    Bugfix:
    my $valid_re = qr/^(?:$valid)$/;
    Without the grouping there will be strange things happening ;-). Apart from that, depending on the situation, you might want to replace $ at the end of the regex with \z depending on whether you want to allow newlines behind the valid items (your solution) or not (\z).

    Update: To see the strange things happening, try

    my @valid = qw/foo bar baz/; my @a_bunch_of_inputs = qw/fooZZZ ZZbarZZ ZZZbaz foobaz foo bar baz/;
    and all of the inputs will produce okay.

    -- Hofmator

    Code written by Hofmator and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-25 10:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found