develooper Front page | perl.perl5.porters | Postings from October 2016

Re: Extend the fat comma to deal with undef

Thread Previous | Thread Next
From:
Paul "LeoNerd" Evans
Date:
October 6, 2016 10:54
Subject:
Re: Extend the fat comma to deal with undef
Message ID:
20161006115402.3611a8f0@shy.leonerd.org.uk
On Thu, 6 Oct 2016 05:59:28 +0100
Sam Kington <sam@illuminated.co.uk> wrote:

> The other one is similar: it’s about optional elements of hashes.
> It’s the sort of thing where you end up writing;
> 
>     optional(
>         thing => $thing,
>         (exists $params{this} ? this => $params{this} : ()),
>         (exists $params{that} ? that => $params{that} : ()),
>     );
> 
> until you get fed up and you refactor it as
> 
>     my %optional_params = (thing => $thing);
>     for (qw(this that)) {
>        $optional_params{$_} = $params{$_} if $params{$_};
>     }
>     optional(%optional_params);
> 
> but who are you fooling? It’s still nasty. The fact that you used $_
> doesn’t hide the fact that you repeated the name of the variable all
> over the place, or that you needed a custom loop.
> 
> I wonder if you could do something interesting with the fat comma?
> 
> For instance:
> 
>     mandatory(
>         thing => $thing,
>         this =>! this_does_something(),
>         that =>! that_does_something(),
>     );
> 
> and
> 
>     optional(
>         thing => $thing,
>         this =>? $params{this},
>         that =>? $params{that},
>     );

That's what hash slices are for

    optional(
       thing => $thing,
       %{$params}{qw( this that )}
    )

-- 
Paul "LeoNerd" Evans

leonerd@leonerd.org.uk      |  https://metacpan.org/author/PEVANS
http://www.leonerd.org.uk/  |  https://www.tindie.com/stores/leonerd/

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