Anti-nuisance lawsuit warning: The purpose of these notes is to remind me, Zoegond, of stuff or to help me work stuff out. They may contain mistakes.

Quick

  • ($a, $b....) = unpack("A2A7...", $packed)
  • push( array, list )

Friday, February 26, 2010

Perl regular expressions and interpolation

Q. How to use, in a s/// substitution, a string defined elsewhere in your program, or supplied by the user, and that contains variable substitions/grouping references?

A. Use double evaluation, and ensure the string has quotes actually in it, and (in the case of a string defined in the program) that any references to groups are escaped so that they aren't interpreted at compile time. Escaping group references should not be done in a user-supplied string, or a string read from a file etc.

(On the pattern side of the s///, you only need watch out for $, @ etc which might cause unwanted interpolation in your pattern).

$replace = '"\$1z"'; # check the quotes carefully! it's ' " blah " '
$text = "apple";
$pattern = "a(..)";
$text =~ s/$pattern/$replace/ee;
# or $text =~ s/$pattern/eval $replace/e;

# or
$replace = "\$1z";
$text = "apple";
$pattern = "a(..)";
$text =~ s/$pattern/qq("$replace")/ee;
# NOT $text =~ s/$pattern/"$replace"/ee;

Remember that in all these examples, the string the user types, or the string in the file etc, should not have interpolation escapes, eg user should type literally

"$1z"

(or, if the qq("") form is being used, just

$1z
)

As the internet points out

What is likely confusing is that both of these statements yield the same result:

$text2 =~ s/$match/$replace/;
$text2 =~ s/$match/$replace/e;

Followers

Blog Archive