Alex
Alex

Reputation: 10126

On-fly regexp modification

I have the following set of strings:

my @strings = {"/str1/", "/str2/", "/str3/"};

I need to modify the regular expression on-fly using something like this:

foreach $string (@strings )
{
     if($line =~ $string)
     {
         #do something
     }
}

Unfortunately, this code doesn't seem to work as the #do something not happens.

I am not pretty sure that it is correct code. Is it possible in perl at all?

Upvotes: 0

Views: 122

Answers (3)

Miguel Prz
Miguel Prz

Reputation: 13792

Try this:

use strict;
use warnings;

my @regexprs = ( qr/str1/, qr/str2/, qr/str3/ );

my $line = "-- str2 --";
foreach my $re (@regexprs )
{
     if($line =~ $re)
     {
         print "match: $line  $re\n";
     }
}

Upvotes: 2

amon
amon

Reputation: 57640

The array syntax in Perl is just

my @array = ($elem1, $elem2, ...);

or with arrayrefs:

my $arrayref = [$elem1, $elem2, ...];

You can quote regex objects with the qr operator

my $regex = qr/str1/;
if ($string =~ $regex) { ... }

which may be preferable (avoids double escaping in edge cases).

Upvotes: 0

ikegami
ikegami

Reputation: 385917

my @patterns = ("pattern1", "pattern2", "pattern3");

for my $pattern (@patterns) {
   if ($line =~ $pattern) {
      # $line matches $pattern
   }
}

or

my @strings = ("string1", "string2", "string3");

for my $string (@strings) {
   if ($line =~ /\Q$string/) {
      # $line contains $string
   }
}

Upvotes: 3

Related Questions