So I have two variables
$x = q(foo);
$y = q(bar);
My goal is to use them in a third variable with an underscore between them i.e. foo_bar
. There are lots of ways to do this, but I wanted to use qq
so
$z = qq($x_$y);
This gives the following error
Global symbol "$x_" requires explicit package name at test.pl line 45.
Execution of C:\test.pl aborted due to compilation errors.
So I had to use curly brackets with the variable x
to make it work
$z = qq(${x}_$y);
Why does underscore not work with qq
? Why do I need curly brackets in this case?
That's because _
counts as a letter in identifiers (such as variable names).
When you write "$x_$y"
, Perl thinks you're trying to interpolate two variables, $x_
and $y
. Similarly, when you write "$foo$bar"
, Perl thinks you're trying to interpolate $foo
and $bar
(not $f . 'oo' . $bar
or $fo . 'o' . $bar
or any other combination).
The general rule is: Names extend as far to the right as possible (that is, Perl chooses the longest possible interpretation for identifiers).