Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a different way to concatenate variables in Perl?

I accidentally wrote the following line of code:

print "$linenumber is: 
" . $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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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: 
" . $linenumber;

It can be rewritten as:

print "$linenumber is: 
$linenumber";

To avoid string interpolation, use single quotes:

print '$linenumber is: ' . "
$linenumber";  # No need to escape `$`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...