警告没有发送到stderr

Deg*_*taf 1 perl

我有一个函数检查数据是否有效(即非负),并应该警告然后退出子.我遇到的问题是警告被抑制了.任何人都可以解释为什么警告被抑制?

#!/usr/bin/perl
use strict;
use warnings;

my $a = b();
print "Function returned $a\n";

sub b
{
    my $a = -1;
    ($a >= 0) || (warn "\$a is negative" && return 0);
    print "Passed negative check\n";
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

我收到的输出是

Function returned 0
Run Code Online (Sandbox Code Playgroud)

ike*_*ami 7

优先权问题.

warn "\$a is negative" && return 0
Run Code Online (Sandbox Code Playgroud)

手段

warn("\$a is negative" && return 0)
Run Code Online (Sandbox Code Playgroud)

你要

warn "\$a is negative" and return 0
Run Code Online (Sandbox Code Playgroud)

要么

warn("\$a is negative") && return 0
Run Code Online (Sandbox Code Playgroud)

更好的是,应用这两个变化.

warn("\$a is negative") and return 0
Run Code Online (Sandbox Code Playgroud)

当你在参数列表周围省略parens时要小心陷阱.

一般地,使用andor如果RHS表达由一个流量控制表达的如die,return,next,last,redoexit.


实际上,你为什么要检查什么warn回报?你真的想要

warn("\$a is negative"), return 0
Run Code Online (Sandbox Code Playgroud)

要么

do { warn "\$a is negative"; return 0 }
Run Code Online (Sandbox Code Playgroud)

所以我们得到了

$a >= 0
   or warn("\$a is negative"), return 0;
Run Code Online (Sandbox Code Playgroud)

要么

$a >= 0
   or do {
      warn "\$a is negative";
      return 0;
   };
Run Code Online (Sandbox Code Playgroud)

但我怀疑大多数人都希望看到

if ($a < 0) {
   warn "\$a is negative";
   return 0;
}
Run Code Online (Sandbox Code Playgroud)