Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Perl interpolating variable in single-quoted string?

Tags:

perl

Consider the following Perl script:

#!/usr/bin/perl

foreach(split '$$', 'A$$B'){ print; }
print "\n";
foreach(split '\$\$', 'A$$B'){ print; }
print "\n";

Given the well-known fact that Perl performs variable interpolation in double-quoted strings only, the $$ in the single-quoted strings above is expected to be treated as a literal $$ rather than the PID of the current process. Thus, the expected output of the script is

AB
AB

However, when running this script with both Perl v5.34.1 and an online Perl compiler, the following is outputted instead:

A$$B
AB

This seems to imply that when using '$$' in split, the $$ is getting interpolated, contrary to the specification that single quotes perform do not perform variable interpolation.

This unexpected result cost me considerable time debugging an otherwise-functional Perl program. While I succeeded in resolving the issue by escaping the dollar signs in the single-quoted string used for split, I am still curious why this behavior occurred, and I was unable to find any sources suggesting it is expected.

Is this a bug in Perl, or are there scenarios where interpolation into a single-quoted string is expected to occur?

like image 850
Math Rules Avatar asked Jan 22 '26 16:01

Math Rules


1 Answers

The first argument to split is a regular expression pattern, even if single-quoted. So, your first case has two end-of-line anchors whereas the second splits on two dollar signs.

Update: ikegami rightly clarifies that split has a special case when the pattern is a single space character string. In this case it works like awk, trimming leading whitespace and splitting on /\s+/.

like image 72
pilcrow Avatar answered Jan 25 '26 07:01

pilcrow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!