如何解决这种“在无效上下文中无用使用变量"的情况? [英] How can I resolve this case of "Useless use of a variable in a void context"?

查看:50
本文介绍了如何解决这种“在无效上下文中无用使用变量"的情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何解决在无效上下文中无用使用变量"这种情况?

How can I resolve this case of "Useless use of a variable in a void context"?

例如:

  my $err = $soap_response->code, " ", $soap_response->string, "\n";
  return $err;

我收到诸如在无效上下文中无用使用变量"之类的警告?为什么?我该如何解决?

I get warnings like "Useless use of a variable in a void context"? Why? How can I resolve it?

推荐答案

如果要连接参数,请使用 "." 运算符或 join:

In case you want to concatenate the arguments, use the "." operator or join:

my $err = $soap_response->code. " ". $soap_response->string. "\n";
my $err = join '', $soap_response->code, " ", $soap_response->string, "\n";

接下来就是 Perl 给你警告的原因.

Next is why Perl gives you warnings.

您正在分配给一个标量变量 $err,并且分配的右侧在标量上下文中进行评估.

You're assigning to a scalar variable $err, and the right-hand side of the assignment is evaluated in scalar context.

二进制,"是逗号运算符.在标量上下文中,它在 void 上下文中评估其左参数,将该值丢弃,然后在标量上下文中评估其右参数并返回该值.

Binary "," is the comma operator. In scalar context it evaluates its left argument in void context, throws that value away, then evaluates its right argument in scalar context and returns that value.

对变量或常量求值并丢弃该值是没有用的.perl 会警告你这一点.

Evaluating a variable or a constant and throwing that value away is useless. And perl warns you about this.

仅供参考:您的代码可能存在的另一个问题:

FYI: Another possible issue with your code:

my $err = $soap_response->code, " ", $soap_response->string, "\n";

分配具有更高的优先级,因此:

The assignment has higher precedence so that is:

(my $err = $soap_response->code), " ", $soap_response->string, "\n";

请参阅 Perl 运算符和优先级逗号运算符了解更多信息.

See Perl operators and precedence and the Comma operator for more information.

这篇关于如何解决这种“在无效上下文中无用使用变量"的情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆