Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: matching elements in a list in a logical OR fashion

by Zaxo (Archbishop)
on Jun 15, 2004 at 03:46 UTC ( #366760=note: print w/ replies, xml ) Need Help??


in reply to matching elements in a list in a logical OR fashion

This is one of my favorite tricks,

my $re = do { local $" = '|'; qr/@array/; }; if ($bigstring =~ /$re/ ) { #... }
The customary way is to join '|', @array in constructing the regex.

If @array has regex metacharacters, it may be needful to escape them:

my $re = do { local $" = '|'; qr/@{[map { quotemeta } @array]}/; };

After Compline,
Zaxo


Comment on Re: matching elements in a list in a logical OR fashion
Select or Download Code
Re^2: matching elements in a list in a logical OR fashion
by meetraz (Hermit) on Jun 15, 2004 at 04:03 UTC
    This might be even faster, depending on what's in @array...
    Regex::Presuf works wonders, and /o usually helps too.

    use strict; use Regex::PreSuf; my @array = qw( foo bar baz ); my $re = presuf(@array); my $bigstring = 'whatever'; if ($bigstring =~ /$re/o) { print "it matched"; }
Re^2: matching elements in a list in a logical OR fashion
by NodeReaper (Curate) on Jun 15, 2004 at 06:21 UTC
    This node was taken out by the NodeReaper on Tue Jun 15 06:01:16 2004 (EST)
    Reason: valdez delete, empty node

    For more information on this node visit: this

Re^2: matching elements in a list in a logical OR fashion
by didier (Vicar) on Jun 15, 2004 at 06:25 UTC
    Thank for that, Zaxo.
    That's really nice.

Re^2: matching elements in a list in a logical OR fashion
by hardburn (Abbot) on Jun 15, 2004 at 13:57 UTC

    For the metacharacters case, how about this:

    my $re = do { local $" = '\E|\Q'; qr/\Q@array\E/; };

    That lets you ditch the map and array refernceing/dereferencing inside the regex. Though it is arguably not as clear.

    ----
    send money to your kernel via the boot loader.. This and more wisdom available from Markov Hardburn.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (9)
As of 2014-09-20 09:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (157 votes), past polls