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?
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+/
.