如何在Perl中连接变量?

时间:2012-08-02 17:08:09

标签: string perl concatenation string-concatenation

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

print "$linenumber is: \n" . $linenumber;

这导致输出如:

22 is:
22

我在期待:

$linenumber is:
22

然后我想知道。它必须将双引号中的$linenumber解释为对变量的引用。 (多酷啊!)

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

6 个答案:

答案 0 :(得分:13)

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

print "\$linenumber is: \n" . $linenumber;

可以改写为:

print "\$linenumber is: \n$linenumber";

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

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

答案 1 :(得分: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 ..."

答案 2 :(得分:3)

在Perl中,任何使用双引号构建的字符串都将被插值,因此任何变量都将被其值替换。像许多其他语言一样,如果你需要打印$,你将不得不逃避它。

print "\$linenumber is:\n$linenumber";

OR

print "\$linenumber is:\n" . $linenumber;

OR

printf "\$linenumber is:\n%s", $linenumber;

Scalar Interpolation

答案 3 :(得分:2)

如果您从

更改代码
print "$linenumber is: \n" . $linenumber;

print '$linenumber is:' . "\n" . $linenumber;

print '$linenumber is:' . "\n$linenumber";

它会打印

$linenumber is:
22

当我想要打印变量名时,我觉得有用的是使用单引号,这样内部的变量就不会被转换为它们的值,使代码更容易阅读。

答案 4 :(得分:1)

在制定此回复时,我发现this webpage解释了以下信息:

###################################################
#Note that when you have double quoted strings, you don't always need to concatenate. Observe this sample:

#!/usr/bin/perl

$a='Big ';
$b='Macs';
print 'I like to eat ' . $a . $b;

#This prints out:
#  I like to eat Big Macs

###################################################

#If we had used double quotes, we could have accomplished the same thing like this:

#!/usr/bin/perl

$a='Big ';
$b='Macs';
print "I like to eat $a $b";

#Printing this:
#  I like to eat Big Macs
#without having to use the concatenating operator (.).

###################################################

#Remember that single quotes do not interpret, so had you tried that method with single quotes, like this:


#!/usr/bin/perl

$a='Big ';
$b='Macs';
print 'I like to eat $a $b';
#Your result would have been:
#  I like to eat $a $b
#Which don't taste anywhere near as good.

我认为这会对社区有所帮助,所以我问这个并回答我自己的问题。其他有用的答案非常受欢迎!

答案 5 :(得分:1)

你可以反斜杠$按字面打印。

print "\$linenumber is: \n" . $linenumber;

打印您期望的内容。如果您不希望perl插入变量名,您也可以使用单引号,但"\n"将按字面插值。