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

Re: Using smart matching to find whether an array contains a string

Thread Previous | Thread Next
Eric Brine
January 25, 2011 14:44
Re: Using smart matching to find whether an array contains a string
Message ID:
On Tue, Jan 25, 2011 at 1:08 PM, Ed Avis <> wrote:
> 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

It's not missing at all.

Any   Any      string equality   $a eq $b

Are you suggesting we should replace the above with a long list that
includes the following?

Hash  String   string equality   $a eq $b
Array String   string equality   $a eq $b
Regex String   string equality   $a eq $b

Explaining that "Any" includes "String" sounds like the job of a *book* to

> From the new perlsyn it looks like 'match against an array element' might
> what I want to use, as
>    $x ~~ @a
> but this has some surprising behaviour:
>    % perl -E '@a = (1); say "1 x" ~~ @a'
>    1

Not surprising without warnings suppressed:

$ perl -wE'@a = (1); say "1 x" ~~ @a'
Argument "1 x" isn't numeric in smart match at -e line 1.

> But is there any way to get a plain string match, at least for
> scalars which are not references?

Make sure the array only contains strings.

"1 x" ~~ [ map "$_", @a ]

In general, smart-matching only makes sense with known values on the
right-hand side. It might make more sense to use grep or similar when that's
not the case.

grep "1 x" eq $_, @a
any { "1 x" eq $_ } @a

- Eric

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