develooper Front page | perl.perl5.porters | Postings from September 2012

Re: given/when/~~ "final" thoughts (ha ha ha)

Thread Previous | Thread Next
From:
Smylers
Date:
September 17, 2012 02:00
Subject:
Re: given/when/~~ "final" thoughts (ha ha ha)
Message ID:
20120917085949.GI1846@stripey.com
Father Chrysostomos writes:

> Ricardo Signes wrote:
> 
> > The last thing I'd said about smartmatch was:
> > 
> >   $x ~~ undef                                                                   
> >   $x ~~ $overloaded_object                                                      
> >   $x ~~ sub {}                                                                  
> >   $x ~~ regex                                                                   
> >   ...or fail                                                                    
> > 
> > ...with when:
> > 
> >   when ("foo") # str eq
> >   when (12345) # num ==
> >   when ($x)    # ~~
> >   when { ... } # block evaluates true
> 
> I discovered a gotcha with that:
> 
>     given(42) {
>       when {/4(.)/} {
>         print $1, "\n"; # prints nothing
>       }
>     }

> This would need to be documented.

Would a warning make sense as well? "Capture group in when {/PATTERN/}
isn't accessible" or similar if a when {...} block uses capturing parens
and doesn't use \1 or similar later in the pattern.

The documentation mainly needs to point readers towards the form that
does work:

        when (qr/4(.)/) {

> I found Smylers’ argument (<20120905143040.GZ1742@stripey.com>)
> convincing

Thanks -- glad it was of use.

> so I implemented it like this:
> 
>  $x ~~ undef
>  $x ~~ $overloaded
>  $x ~~ sub{}
>  $x ~~ qr//
>  $x ~~ $anthing_else # fall back to eq
> 
> But that makes ~~[] do the wrong thing silently in existing code, so
> adding this before the last case would improve it:
> 
>  $x ~~ $other_ref # croak

Yes, good point.

How about restricting $other_ref to mean 'other references that aren't
blessed objects with overloaded stringification'? That way things like
Class::Path objects still just match as strings, without having to
explicitly stringify them.

> Two things I’m not volunteering to do are:
>   • Write the documentation (don’t forget to warn about $1 being
>     unavailable in when {/(1)/} { $1 })

I volunteer to do that.

Cheers

Smylers
-- 
New series of TV puzzle show 'Only Connect' (some questions by me)
Mondays at 20:30 on BBC4, or iPlayer: http://www.bbc.co.uk/onlyconnect

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