0

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:

  • Hello #NAME#
  • This is only intended for #NAME#
2
  • Two things: # is not a metacharacter (and therefore doesn't need to be escaped), and you probably want to use \Q...\E to quote any potential metacharacters contained inside your variable. Have you tried anything yet? Commented Jul 27, 2017 at 20:41
  • @MattJacob I'm rather inexperienced with Perl and am editing someone else's script. I have not because I kind of need to know if this is possible for the type of script I am creating. Basically it will look for different strings in different templates for emails. Based on prior criteria the appendValue will be different. Commented Jul 27, 2017 at 20:44

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I inherited this script in a language I have 0 experience with and I don't have much experience with Regex either. I will try this and mark you as answered if it works. Or be back with more questions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.