如何在Perl中连接变量?

ken*_*dds 6 string perl concatenation string-concatenation

是否有不同的方法来连接perl中的变量?我不小心写了以下代码行:

print "$linenumber is: \n" . $linenumber;
Run Code Online (Sandbox Code Playgroud)

这导致输出如下:

22 is:
22
Run Code Online (Sandbox Code Playgroud)

我在期待:

$linenumber is:
22
Run Code Online (Sandbox Code Playgroud)

所以我想知道.它必须将$linenumber双引号中的内容解释为对变量的引用.(挺酷的!)

我只是想知道:使用这种方法有什么警告,有人可以解释一下这是如何工作的吗?

Ala*_*avi 13

使用双引号时会发生变量插值.因此,需要转义特殊字符.在这种情况下,你需要逃避$:

print "\$linenumber is: \n" . $linenumber;
Run Code Online (Sandbox Code Playgroud)

它可以改写为:

print "\$linenumber is: \n$linenumber";
Run Code Online (Sandbox Code Playgroud)

要避免字符串插值,请使用单引号:

print '$linenumber is: ' . "\n$linenumber";  # No need to escape `$`
Run Code Online (Sandbox Code Playgroud)


Zon*_*Zon 5

我喜欢 .= 运算符方法:

#!/usr/bin/perl
use strict;
use warnings;

my $text .= "... contents ..."; # Append contents to the end of variable $text.
$text .= $text; # Append variable $text contents to variable $text contents.
print $text; # Prints "... contents ...... contents ..."
Run Code Online (Sandbox Code Playgroud)