develooper Front page | perl.perl5.porters | Postings from June 2022

Re: Pre-{Pre-RFC} - match/case syntax

Thread Previous | Thread Next
From:
Alexander Hartmaier
Date:
June 27, 2022 11:23
Subject:
Re: Pre-{Pre-RFC} - match/case syntax
Message ID:
CAB49QrbHD2u2AgJEaHQ1k28hsnFEUCMiVP+YUbmG0X-eX2a=gA@mail.gmail.com
On Mon, Jun 27, 2022 at 11:11 AM Darren Duncan <darren@darrenduncan.net>
wrote:

> On 2022-06-24 3:17 p.m., Paul "LeoNerd" Evans wrote:
> >    my $n = ...;
> >
> >    match($n : ==) {
> >       case(1) { say "It's one" }
> >       case(2) { say "It's two" }
> >       case(3) { say "It's three" }
> >       case(4), case(5)
> >               { say "It's four or five" }
> >       default { say "It's something else" }
> >    }
>
> I consider that the best part of this is you specify inline the exact
> comparison
> operator or sub to use, the "==" in this case, meaning that the semantics
> of the
> matching is completely explicit, rather than some implicit complicated
> logic.
>
> This should be generic and configurable in the same way map/grep/sort etc
> are.
>

I'd prefer the comparison operator per case so I can for example call isa
on an exception object to check if it's an exception object or just a
string.
That can be done using given/when from feature "switch", but as this says
it's experimental I haven't used it.
The section
https://perldoc.perl.org/perlsyn#Experimental-Details-on-given-and-when
this to explain why. To me it reads like "don't use it before v5.18". I
guess it wasn't declared non-experimental at or shortly after v5.18 because
it uses the experimental smartmatch underneath, although not mandatory.

Syntax that doesn't need to to write $_:

given|match|for|foreach ($foo) {
    when|case (== 3) {
    }
    when|case (eq 'bar') {
    }
    when|case (->isa('X::File::NotFound') {
    }
}

PS: I don't care what the keywords are called so I included some which are
already mentioned.

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