How to avoid variable substitution in Perl regex?

214 views Asked by At

I have the following regex:

my ($pkg) = ( $xmldirname =~ /$db(.*)^/ );

What it should do is: check if the xmldirname starts ($) with "db" and take the rest of the string into $pkg.

What it does is: "Global symbol $db requires explicit package name".

How do I do this? Using qr// didn't work, either.

Yes, ok, I see. $ is end, not start. I'm sorry....

3

There are 3 answers

0
Toto On BEST ANSWER

It seems to me that you misused the anchor.

What it should do is: check if the xmldirname starts ($) with "db" and take the rest of the string into $pkg.

Use this:

my ($pkg) = ( $xmldirname =~ /^db(.*)$/ );

You could also remove the terminal $:

my ($pkg) = ( $xmldirname =~ /^db(.*)/ );
2
el.pescado - нет войне On

You can escape $ using backslash (\) so that it loses its special meaning:

my ($pkg) = ( $xmldirname =~ /\$db(.*)^/ );

Alternatively, you can specify arbitrary delimiter for m (in fact, any quote-like operator) operator, and using single quote (') disables string interpolation:

my ($pkg) = ( $xmldirname =~ m'$db(.*)^' );

See Quote and Quote-like Operators

0
nu11p01n73R On
  • You can escape the $

  • Add the anchor ^ at the begining of the regex and not at the end

The code can be

my ($pkg) = ( $xmldirname =~ /^\$db(.*)/ );

Test

$xmldirname = '$dbhello';
my ($pkg) = ( $xmldirname =~ /^\$db(.*)/ );
print $pkg;

will give output as

hello