jonah_w
jonah_w

Reputation: 1032

Useless use of negative pattern binding (!~) in void context

If both strings have spaces or neither has spaces, then do something.

my $with_spaces = $a =~ / / and $b =~ / /;
my $no_spaces = $a !~ / / and $b !~ / /;
if ($with_spaces or $no_spaces) {
    dosomething();
}

But this code gives an error:

Useless use of negative pattern binding (!~) in void context.

Did I do something wrong here?

Upvotes: 4

Views: 181

Answers (1)

jhnc
jhnc

Reputation: 16817

The lines:

my $with_spaces = $a =~ / / and $b =~ / /;
my $no_spaces = $a !~ / / and $b !~ / /;

are equivalent to:

(my $with_spaces = $a =~ / /) and ($b =~ / /);
(my $no_spaces = $a !~ / /) and ($b !~ / /);

Either use && instead of and, or add parentheses to change the precedence:

my $with_spaces = $a =~ / / && $b =~ / /;
my $no_spaces = ($a !~ / / and $b !~ / /);

Upvotes: 7

Related Questions