我想将右侧的整个字符串分配给左侧的变量
my $branch = "\t" x $level, "$level -> $treeRoot\n";
where$level是一个数字,$treeRoot是一个字符串。当我尝试打印$branch时,它说变量为空。
应该发生的事情的一个例子:说$levelis5和$treeRootis "string"。我想$branch取值:
my $branch = "\t\t\t\t\t5 -> string\n";
Replace
my $branch = "\t" x $level, "$level -> $treeRoot\n";
with
my $branch = "\t" x $level . "$level -> $treeRoot\n";
. is the string concatenation operator.
二进制“,”是逗号运算符。在标量上下文中,它计算其左参数,丢弃该值,然后计算其右参数并返回该值。这就像 C 的逗号运算符。
赋值运算符的优先级高于二进制逗号。基本上你的代码相当于:
(my $branch = "\t" x $level), "$level -> $treeRoot\n";
或者用逗号运算符写出:
my $branch = "\t" x $level;
"$level -> $treeRoot\n";
首先my $branch = "\t" x $level是评估。然后,"$level -> $treeRoot\n"被评估。但它是 void 上下文中的字符串。
为了进一步探索这一点,如果您在右侧加上括号:
my $branch = ("\t" x $level, "$level -> $treeRoot\n");
现在赋值本身不再是逗号运算符左侧的一部分。$branch变量被赋值,或者是逗号运算符的"$level -> $treeRoot\n"右边。
如果将逗号运算符更改为.,则字符串连接运算符:
my $branch = "\t" x $level . "$level -> $treeRoot\n";
您的代码将按预期工作。
PS如果你添加如果你添加:
use strict;
use warnings;
在你的文件的顶部,Perl 会给你一个不正确的警告:
Useless use of string in void context
strict拥有并warnings启用它通常是一个好主意。