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

Suppose I want to use a variable in a regular expression like this: /$var_*/ I want the regular expression to mach the content of the variable and a underscore plus something else. But the complier offcourse assumes that the name of the variable is $var_ and says that there is no such variable. So what do you suggest me to do. Thank you for any help.

Replies are listed 'Best First'.
Re: Variable in regexp
by jwkrahn (Abbot) on Mar 22, 2011 at 00:20 UTC

    Put the variable name in braces like this: /${var}_*/.

Re: Variable in regexp
by toolic (Bishop) on Mar 22, 2011 at 00:25 UTC
    Another way is to use whitespace in the regex with the //x modifier (perlre)
    / $var _ /x
      The disadvantage is that that only works in patterns. The ${var}_ method also works in double quoted strings.
Re: Variable in regexp
by umasuresh (Hermit) on Mar 22, 2011 at 10:41 UTC
    Are you expecting something like this?
    my $var = "only"; my $str = "only_once"; if($str =~ /($var)\_(.*)/) { print "$1\t$2\n"; }