Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
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

Replies are listed 'Best First'.
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 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.

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://366760]
help
Chatterbox?
[LanX]: But you can use CSS to hide it
[LanX]: and disoplay the data permanently in your peronal nodelet
[marinersk]: I saw that you could post it on the Personal Nodelet, but you have to provide the content also. No way to auto-populate it. Not that this would solve my distraction problem...
[LanX]: there are template variables to "Auto-populate" it
[marinersk]: Yeah, someday I might become interested enough to poke around PerlMonks more internally. Most of the fancy stuff is way down on my to do list.
[LanX]: Yeah ...
[LanX]: no variable for votes_left
[marinersk]: Ah, well. I will continue to deal with it, as I have. Thanks for poking about, though.
[LanX]: you are welcome! :)

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2017-05-29 14:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?