According to this comment:
You also should not use single quotes in
print ">>${ '_<$filename' }<<\n"
. Instead try:print ">>${ \"_<$filename\" }<<\n"
I always thought that differences between "
and '
are only that the string is interpreted or not.
I want to ask why at this context:
print ">>${ \"_<$filename\" }<<\n"
print ">>${ '_<$filename' }<<\n"
perl prints different values?
Why I should use \"
instead of just '
here?
What happens is that in both cases, $filename
is not interpolated by the outer string (">>...<<\n"
), but rather by ${ ... }
. (this is just deduction from the behavior). This means that in ">>${ '_<$filename' }<<\n"
, $filename
isn't interpolated at all, while it is in ">>${ \"_<$filename\" }<<\n"
.
If it was interpolated by the outer string, then you'd ran into some troubles if your string was containing quotes:
$filename = "ab'cd";
If interpolation was done by the outer string, then "${'$filename'}"
would be equivalent to "${'ab'cd'}"
, which is a syntax error. Or maybe rather to "${ab'cd}"
, which is equivalent to "${ab::cd}"
; not what you want either.
Whereas if the interpolation is done by ${}
, then in "${'$filename'}"
, ${...}
is really ${"$filename"}
(without the escaped double-quotes), which interpolates $filename
, and you get something like ${"ab'cd"}
, like you'd want.
Consider this example:
$abcd = "First var";
${'$v'} = "Second var";
$v = "abcd";
say "${\"$v\"}"; # prints "First var"
say "${'$v'}"; # prints "Second var"
It shows that with "${\"$v\"}"
, $v
was interpolated, whereas with "${'$v'}"
, it wasn't.