【问题标题】:Perl - assigning a composite string to a variablePerl - 将复合字符串分配给变量
【发布时间】:2013-06-06 11:59:05
【问题描述】:

我想把右边的整个字符串赋给左边的变量

my $branch =  "\t" x $level, "$level -> $treeRoot\n";

其中$level 是一个数字,$treeRoot 是一个字符串。当我尝试打印 $branch 时,它说变量为空。

应该发生的事情的一个例子:假设$level5 并且$treeRoot"string"。我想$branch 取值:

my $branch = "\t\t\t\t\t5 -> string\n";

【问题讨论】:

    标签: string perl assign


    【解决方案1】:

    替换

    my $branch = "\t" x $level, "$level -> $treeRoot\n";
    

    my $branch = "\t" x $level . "$level -> $treeRoot\n";
    

    . 是字符串连接运算符。

    【讨论】:

      【解决方案2】:

      来自the , 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";
      

      您的代码将按预期工作。

      附:如果添加 如果添加:

      use strict;
      use warnings;
      

      在你文件的顶部,Perl 会警告你有什么不对劲的地方:

      Useless use of string in void context
      

      启用strictwarnings 通常是个好主意。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-12
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 2018-07-24
        • 2013-02-23
        • 1970-01-01
        • 2013-04-18
        相关资源
        最近更新 更多