develooper Front page | perl.perl5.porters | Postings from January 2011

Using smart matching to find whether an array contains a string

Thread Next
Ed Avis
January 25, 2011 10:09
Using smart matching to find whether an array contains a string
Message ID:
This question is about the smart match operator ~~ and about its documentation.
Is it possible to find whether an array contains a given string?

In perl 5.10.0 I was using

    @a ~~ $x

but from a glance at perlsyn(1) it appears that this does something different in
5.10.1 and later.  I am not posting to complain about that change - it was well
signposted that smart matching in 5.10.0 was an experimental feature - but I
suggest an explicit entry in the 'Smart matching in detail' section to document
the case when $a is an array and $b is a string, which is currently missing.

From the new perlsyn it looks like 'match against an array element' might be
what I want to use, as

    $x ~~ @a

but this has some surprising behaviour:

    % perl -E '@a = (1); say "1 x" ~~ @a'

That is a consequence of this:

    % perl -E 'say "1 x" ~~ 1'

which is documented in the 'Any / Num' case in perlsyn (and gives a warning
with -w).  But is there any way to get a plain string match, at least for
scalars which are not references?

If not, I could instead use

    List::MoreUtils::any { $_ eq $x } @a

Ed Avis <>

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About