Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 `$`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...