Elias
Elias

Reputation: 2632

Combining a Variable and Regular Expression in Perl

I have the code:

$TEMP =~ s/\#NAME\#/$customerName/g;

Where I am replacing #NAME# with the value in $customername using Regex. What I want to do is append a variable onto the end of NAME.

So I want to do something like:

$TEMP =~ s/\#NAME . $appendValue\#/$customerName/g;

so it will essentially be:

$TEMP =~ s/\#NAME_1\#/$customerName/g;

Would this work or is there a proper way to handle this?


Test Cases:

Upvotes: 0

Views: 468

Answers (1)

choroba
choroba

Reputation: 241928

The pattern interpolates variables, so no concatenation operator is needed:

$TEMP =~ s/#NAME$appendValue#/$customerName/g;

You might need to protect special characters in the variable, though, so use \Q...\E:

$TEMP =~ s/#NAME\Q$appendValue\E#/$customerName/g;

# is not special in a regex, so no backslash is needed (but it doesn't hurt).

Upvotes: 3

Related Questions