jack
jack

Reputation: 77

Perl - add a variable in a variable

I want add the variable $hostname in the variable $hostame_table appended with _table.

My code:

use Sys::Hostname ();
my $hostname = Sys::Hostname::hostname();
my $hostname_table = "$hostname"+"_table";
print "$hostname_table";

I would like the result to be computername_table.

Upvotes: 1

Views: 1131

Answers (1)

Dave Cross
Dave Cross

Reputation: 69264

What you're looking for here is called "string concatenation". Perl uses a dot (.) as the concatenation operator, not the + which you've tried to use.

$hostname_table = $hostname . '_table';
print $hostname_table;

Update: Another common approach would be to just "interpolate" the values in a double-quoted string.

$hostname_table = "$hostname_table"; # This doesn't work.

Unfortunately, this simple approach doesn't work here as "_table" is valid as part of a variable name and, therefore, Perl doesn't know where your variable name ends. You can get around that by using a slightly more complex syntax which wraps the variable name in { ... }.

$hostname_table = "${hostname}_table";

Upvotes: 5

Related Questions