Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl究竟如何处理运算符链接?_Perl - Fatal编程技术网

Perl究竟如何处理运算符链接?

Perl究竟如何处理运算符链接?,perl,Perl,所以我有一段代码不起作用: print $userInput."\n" x $userInput2; #$userInput = string & $userInput2 is a integer 当然,如果数字大于0,它会打印一次,但如果数字大于1,它不会打印其余的。我来自java背景,我假设它首先进行连接,然后结果将是使用x运算符将自身相乘。但这当然不会发生。现在,当我执行以下操作时,它会工作: $userInput .= "\n"; print $userInput x $use

所以我有一段代码不起作用:

print $userInput."\n" x $userInput2; #$userInput = string & $userInput2 is a integer
当然,如果数字大于0,它会打印一次,但如果数字大于1,它不会打印其余的。我来自java背景,我假设它首先进行连接,然后结果将是使用
x
运算符将自身相乘。但这当然不会发生。现在,当我执行以下操作时,它会工作:

$userInput .= "\n";
print $userInput x $userInput2;
我是Perl新手,因此我想确切地了解链接的情况,以及我是否能够做到这一点。

这是
(串联)运算符小于
x
运算符。因此,结果是:

use strict;
use warnings;
my $userInput = "line";
my $userInput2 = 2;
print $userInput.("\n" x $userInput2);
和产出:

line[newline]
[newline]
这就是你想要的:

print (($userInput."\n") x $userInput2);
这将打印出:

line
line
你问的是运算符优先级。(“链接”通常指方法调用的链接,例如
$obj->foo->bar->baz

Perl文档页面以按优先级顺序列出所有运算符的列表开始
x
与其他乘法运算符具有相同的优先级,
与其他加法运算符具有相同的优先级,因此当然首先计算
x
。(即,“优先级更高”或“绑定更紧密”。)

在Java中,您可以使用括号解决此问题:

print(($userInput . "\n") x $userInput2);
注意,这里需要两对括号。如果只使用内括号,Perl会将其视为指示要打印的参数,如下所示:

# THIS DOESN'T WORK
print($userInput . "\n") x $userInput2;
这将打印字符串一次,然后将
print
的返回值复制若干次。将空格放在
之前没有帮助,因为空格通常是可选的且被忽略。在某种程度上,这是运算符优先级的另一种形式:函数调用绑定得比其他任何东西都紧密

如果您真的不喜欢括号太多,那么可以使用一元
+
运算符击败Perl:

print +($userInput . "\n") x $userInput2;

这将
打印
,因此Perl知道行的其余部分是一个表达式。一元
+
没有任何效果;它的主要用途正是这种情况。

如前所述,这是一个问题,因为重复运算符
x
的优先级高于串联运算符
,这并不是这里发生的全部事情,而且,问题本身来自一个糟糕的解决方案

首先,当你说

print (($foo . "\n") x $count);
您正在做的是将repeation操作符的上下文更改为list context

(LIST) x $count
上述语句的真正含义是(如果
$count==3
):

发件人:

二进制“x”是重复运算符。在标量上下文中,或者如果左操作数未包含在括号中,则返回一个字符串,该字符串由左操作数重复右操作数指定的次数组成。在列表上下文中,如果左操作数包含在括号中,或者是一个列表通过qw/STRING/,它重复列表。如果右操作数为零或负,则根据上下文返回空字符串或空列表

(LIST) x $count
解决方案按预期工作,因为
print
接受列表参数。但是,如果您有其他接受标量参数的对象,例如子例程:

foo(("text" . "\n") x 3);

sub foo {
    # @_ is now the list ("text\n", "text\n", "text\n");
    my ($string) = @_;   # error enters here
    # $string is now "text\n"
}
这是一个细微的差别,可能并不总是能得到想要的结果

对于这种特殊情况,更好的解决方案是根本不使用串联运算符,因为它是冗余的:

print "$foo\n" x $count;
或者甚至使用更普通的方法:

for (0 .. $count) {
    print "$foo\n";
}


x
具有更高的优先级。更高的优先级优先。噢,哇!非常感谢您的解释。我确实尝试了括号,正如您所预期的那样,它是错误的,因为它只有一对。但我认为我理解Perl运算符的优先级。我猜不是!或者
print“$userInput\n”x$userInput2
use feature 'say'
...
say $foo for 0 .. $count;