3

Why the smartmatch operator ~~ says that 0 is not in (0, 5..100)?

print ((0 ~~ (0, 5..100)) ? "Y" : "N");

N

Test it here.

Ωmega
  • 42,614
  • 34
  • 134
  • 203

2 Answers2

5

Make the right hand side an array reference

print ((0 ~~ [0, 5..100]) ? "Y" : "N");

or a named array

@a = (0, 5..100);
print ((0 ~~ @a) ? "Y" : "N");

or a ... whatever this is called (anonymous named array?)

print ((0 ~~ @{[0,5..100]}) ? "Y" : "N");

(0,5..100) is a list but it is not an array, and this is one of the places where the distinction is important.

mob
  • 117,087
  • 18
  • 149
  • 283
  • I know a difference between list and array, but shouldn't this operator work with the list as well? – Ωmega Jan 07 '21 at 18:32
  • Maybe it should, but the [documentation](https://metacpan.org/pod/perlop#Smartmatch-Operator) indicates that the right operand ought to be an `ARRAY`. – mob Jan 07 '21 at 18:36
  • @Ωmega, There's no such things as lists. "List" just means "a number of scalars on the stack". In this case, the number of scalars is always going to be one 1 because `(0, 5..100)` is evaluated in scalar context. – ikegami Jan 07 '21 at 19:46
2

Don't use the broken smart-match operator. 0 ~~ ... is specifically one of the reasons it's considered broken.

Use

grep { $_ } 0, 5..100

or

use List::Util qw( first );

first { $_ } 0, 5..100
ikegami
  • 367,544
  • 15
  • 269
  • 518