rimmern has asked for the wisdom of the Perl Monks concerning the following question:

I need to apply a regex to a string using using a regex value in a string. EG:

my $line = "root (hd1,1)"; my $match = "root \(hd[0-9],[0-9])"; if ($line =~ m/$match/is) { print "match 1 found \n"; }

However, this doesnt work. Is there a different way I should be doing this ?

Replies are listed 'Best First'.
Re: Regex from string
by Zaxo (Archbishop) on May 31, 2006 at 10:32 UTC

    What you have is fine, except for an error in $match. You forgot to escape the right paren. You should use single quotes so that complicated quoting issues don't arise, also.

    Added: The qr operator, as suggested by Samy_rio++, has a lot to recommend it for this.

    After Compline,
    Zaxo

Re: Regex from string
by Samy_rio (Vicar) on May 31, 2006 at 10:34 UTC

    Hi, Try this,

    use strict; use warnings; my $line = "root (hd1,1)"; my $match = qr/root \(hd[0-9],[0-9]\)/i; if ($line =~ $match) { print "match 1 found \n"; }

    Regards,
    Velusamy R.


    eval"print uc\"\\c$_\""for split'','j)@,/6%@0%2,`e@3!-9v2)/@|6%,53!-9@2~j';

Re: Regex from string
by jhourcle (Prior) on May 31, 2006 at 10:42 UTC

    Your double quotes are eating the \ before the paren. (and even if it weren't, you aren't escaping the close paren, and so it'd throw an error).

    You can either use single quotes:

    my $match = 'root \(hd[0-9],[0-9]\)';

    or the 'qr' operator:

    my $match = qr{root \(hd[0-9],[0-9]\)};

    I vaguely remember someone mentioned a tool for testing regexes ... but I can't remember what it was, and I'm not having much luck w/ the super search

Re: Regex from string
by prasadbabu (Prior) on May 31, 2006 at 10:34 UTC

    You need qr here and escape right paranthesis. Also have a look at perlre.

    my $line = "root (hd1,1)"; my $match = qr/root \(hd[0-9],[0-9]\)/; if ($line =~ m/$match/is) { print "match 1 found \n"; }

    updated: changed qw to qr. Zaxo++ Thanks.

    Prasad

      No. The qw operator returns a list, splitting on whitespace. That will place only the last element of the list, \(hd[0-9],[0-9]\)), in $match.

      After Compline,
      Zaxo