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!).
What are the caveats to using this method and how does this work?
Variable interpolation occurs when you use double quotes. So, special characters need to be escaped. In this case, you need to escape the $
:
print "\$linenumber is: \n" . $linenumber;
It can be rewritten as:
print "\$linenumber is: \n$linenumber";
To avoid string interpolation, use single quotes:
print '$linenumber is: ' . "\n$linenumber"; # No need to escape `$`
I like .=
operator method:
#!/usr/bin/perl
use strict;
use warnings;
my $text .= "... contents ..."; # Append contents to the end of variable $text.
$text .= $text; # Append variable $text contents to variable $text contents.
print $text; # Prints "... contents ...... contents ..."
If you change your code from
print "$linenumber is: \n" . $linenumber;
to
print '$linenumber is:' . "\n" . $linenumber;
or
print '$linenumber is:' . "\n$linenumber";
it will print
$linenumber is:
22
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.
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.
print "\$linenumber is:\n$linenumber";
OR
print "\$linenumber is:\n" . $linenumber;
OR
printf "\$linenumber is:\n%s", $linenumber;
Scalar Interpolation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With