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
From:
Ed Avis
Date:
January 26, 2011 05:08
Subject:
Re: Using smart matching to find whether an array contains a string
Message ID:
loom.20110126T135905-756@post.gmane.org
Aristotle Pagaltzis <pagaltzis <at> gmx.de> writes:

>>But I don't see that 'string equality' is the semantics?
>>
>>    % perl -E '@a = (1, 2, 3); $s = "@a"; say(@a ~~ $s)'
>
>I am not sure what this is supposed to demonstrate, It does not
>look like it tests anything that one would ever want to test.

Yes, I misunderstood the documentation, which says

    Any     Any       string equality          $a eq $b

I was wondering how this 'string equality' rule applies to the case when
the left-hand side is an array and the right-hand side is a scalar.  The above
was my first guess but it's not correct.

In fact, it turns out to be

    % perl -E '@a = (1, 2, 3); $s = \@a; say(@a ~~ $s)'

which is not really any more useful, in the case when the LHS is an array
(rather than, say, a scalar which contains an array reference).

>I get the impression that you have misunderstood something(s)
>more fundamental, rather than that the table of behaviours is
>confusing.

I think that 'string equality' is not a clear explanation because it is not
obvious how 'string equality' applies between an array and a scalar.  The
test used by smart matching is not the same as the 'eq' operator, for example:

    % perl -E '@a = (1, 2, 3); $s = \@a; say(@a ~~ $s); say(@a eq $s)'
    1


So I suggest the one-line 'Any  Any' case in the smart matching documentation
needs some more explicit (if technically redundant) explanation of what happens
when matching an array on the LHS and a scalar on the RHS.

Part of the confusion may be that the documentation talks about 'arrays' when
I suspect it really means array references, with an implicit rule that an array
used on the LHS of the ~~ operator is promoted to an array reference.  That
rule isn't mentioned, except in the context of the 'when' construct.

-- 
Ed Avis <eda@waniasset.com>


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About