Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate variables in Perl

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?

like image 276
kentcdodds Avatar asked Aug 02 '12 17:08

kentcdodds


Video Answer


4 Answers

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 `$`
like image 170
Alan Haggai Alavi Avatar answered Oct 17 '22 03:10

Alan Haggai Alavi


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 ..."
like image 28
Zon Avatar answered Oct 17 '22 04:10

Zon


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.

like image 3
Joe W Avatar answered Oct 17 '22 03:10

Joe W


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

like image 3
Hameed Avatar answered Oct 17 '22 04:10

Hameed