Is there a different way to concatenate variables in perl? I accidentally wrote the following line of code:
print "$linenumber is: \n" . $linenumber;
And that resulted in output like:
22 is:
22
I was expecting:
$linenumber is:
22
So then I wondered. It must be interpreting the $linenumber
in the double quotes as a reference to the variable. (how cool!)
I am just wondering: What are caveats to using this method and could someone explain how this works?
you can backslash the
$
to print it literally.that prints what you were expecting. You can also use single quotes if you don't want perl to interpolate variable names, but then the
"\n"
will be interpolated literally.If you change your code from
to
or
it will print
What I find useful when wanting to print a variable name is to use single quotes so that the variables within will not be translated into their value making the code easier to read.
Variable interpolation occurs when you use double quotes. So, special characters need to be escaped. In this case, you need to escape the
$
:It can be rewritten as:
To avoid string interpolation, use single quotes:
I like
.=
operator method:In Perl any string that is built with double quotes will be interpolated, so any variable will be replaced by its value. Like many other languages if you need to print a
$
, you will have to escape it.OR
OR
Scalar Interpolation
When formulating this response, I found this webpage which explains the following information:
I thought this would be helpful to the community so I'm asking this and answering my own question. Other helpful answers are more than welcome!