在无效上下文中无用的否定模式绑定(!〜)

jon*_*h_w 4 perl

如果两个字符串都包含空格或都不包含空格,请执行某些操作。

my $with_spaces = $a =~ / / and $b =~ / /;
my $no_spaces = $a !~ / / and $b !~ / /;
if ($with_spaces or $no_spaces) {
    dosomething();
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码给出了一个错误:

在无效上下文中无用的否定模式绑定(!〜)。

我在这里做错了吗?

jhn*_*hnc 7

这些行:

my $with_spaces = $a =~ / / and $b =~ / /;
my $no_spaces = $a !~ / / and $b !~ / /;
Run Code Online (Sandbox Code Playgroud)

等效于:

(my $with_spaces = $a =~ / /) and ($b =~ / /);
(my $no_spaces = $a !~ / /) and ($b !~ / /);
Run Code Online (Sandbox Code Playgroud)

使用&&代替and或添加括号以更改优先级

my $with_spaces = $a =~ / / && $b =~ / /;
my $no_spaces = ($a !~ / / and $b !~ / /);
Run Code Online (Sandbox Code Playgroud)