Let's say I have a large array @stuff
and $thing
and I want to know if is $thing
in @stuff
. What is the best way to do this in Perl 6? And with the βbest,β I mean: idiomatic, readable, performing; not necessarily in that order.
In fact, there are two separate cases. One of them is where you need to do a lot of checks for different $thing
s, the other is where you do it only once or several times.
Let's look at the first case first. I think I know (or) the correct answer.
my $set-of-stuff = set @stuff;
for @whatever -> $thing {
do-something-with($thing) if $thing β $set of stuff;
}
You can skip the first line and just say it ... if $thing β @stuff
, but it will almost certainly have much worse performance as the set is created every time.
But now in the second case, I have only one $thing
for verification. The above solution works, of course, but creating a set just to test it once seems a lot of overhead. Label
do-something-with($thing) if $thing β @stuff;
makes a little more sense here, since we call it only once. But still we need to create a kit for one use.
Somewhat more traditional is:
do-something-with($thing) if @stuff.grep($thing);
Or potentially faster:
do-something-with($thing) if @stuff.first($thing);
But this seems less idiomatic, and, of course, the second is less readable than $thing β @stuff
.
I donβt think there is a solution for smart matching, right? Of course this does not work:
do-something-with($thing) if $thing ~~ @stuff;
Any thoughts?