1

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.

1
  • 1
    From perlop: Binary "+" returns the sum of two numbers. Binary "." concatenates two strings. Commented Nov 13, 2018 at 21:35

1 Answer 1

5

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";
Sign up to request clarification or add additional context in comments.

5 Comments

Perhaps throw in a blurb about interpolation as well (I was going to but you've already got the first part done): my $hostname_table = "${hostname}_table";
@stevieb: I considered it, but the need for {...} in this case made it slightly more complicated than I wanted to explain. I'll give it a go :-/
You don't have to, it was just a thought ;)
@stevieb: Done.
++. I just thought it would round out the answer is all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.