Abhijeet N
Abhijeet N

Reputation: 29

How to concatenate Perl variables with a hyphen?

I am trying to concatenate two or three variables with hyphens. Please check the below example.

my $QueueName   = Support;
my $CustomerID  = abc;
my $UserCountry = India;
my $Count       = 12345;

my $Tn = $QueueName.$CustomerID.$UserCountry.$Count;

I am getting the following output:

"$Tn" = SupportabcIndia12345

But I want it like this:

$Tn = Support-abc-India-12345

Upvotes: 1

Views: 2065

Answers (3)

tjwrona
tjwrona

Reputation: 9035

You should be using strict and warnings to enforce good programming habits. While your solution is technically valid Perl it would fail the strict test since you are trying to define variables with "barewords".


To fix this, put these two lines at the top of your code:

use strict;
use warnings;

Then modify your code to fit the rules of the strict module.

ex:

my $QueueName = Support;

should be:

my $QueueName = 'Support';


As for concatenating the variables this will work:

my $Tn = $QueueName.'-'.$CustomerID.'-'.$UserCountry.'-'.$Count;

-or-

my $Tn = "$QueueName-$CustomerID-$UserCountry-$Count";

The join function will also work:

my $Tn = join '-', $QueueName, $CustomerID, $UserCountry, $Count;


Depending on who will be maintaining your code, the first two methods may be more readable to those who are inexperienced with Perl.

Upvotes: 5

Dr.Avalanche
Dr.Avalanche

Reputation: 1996

This isn't good Perl, and wouldn't run under use strict, which you really should be using. If you were, you'd see errors displayed.

Write it like this, instead:

use strict;
use warnings;

my $QueueName   = 'Support';
my $CustomerID  = 'abc';
my $UserCountry = 'India';
my $Count       = '12345';

my $Tn = "$QueueName-$CustomerID-$UserCountry-$Count";
print "$Tn\n";

You have to quote strings. If you want a hyphen you can use the method above to allocate the values separated by a hyphen.

Upvotes: 0

mpapec
mpapec

Reputation: 50637

You can use join() to join list elements with delimiter,

my $Tn = join "-", $QueueName, $CustomerID, $UserCountry, $Count;

Upvotes: 10

Related Questions