Front page | perl.perl5.porters |
Postings from October 2016
Extend the fat comma to deal with undef
Thread Next
From:
Sam Kington
Date:
October 6, 2016 04:59
Subject:
Extend the fat comma to deal with undef
Message ID:
D780158B-D659-4015-B5F0-6EE2FE001656@illuminated.co.uk
Hi,
I’ve been lurking for a while, and I’ve been writing Perl for most of my professional life. But I can’t say that I’m a language designer, or even that I’ve been keeping up too closely with e.g. what the cool Perl 6 kids have been doing. So I suppose this is mostly a post about an annoyance or two, and a hope that others can pick up on this misshapen idea and make it into something useful.
Also, apologies for writing this in my email client rather than a text editor, if smart quotes pop up where programmer's quotes should be.
There are two related things that annoy me about writing Perl at the moment. The first is the way hashes are just lists packed into pairs, so if you say
mandatory(
thing => $thing,
this => this_does_something(),
that => that_does_something(),
);
and this_does_something() returns an empty list, you end with it collapsing to e.g. mandatory(thing => $thing, this => ‘that’, $whatever_that_returned) and Perl complains about an odd-numbered list.
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},
);
So if bar() returned () in list context, ( foo =>! bar() ) would result in ( foo => undef ), but ( foo =>? bar() ) would result in in ().
More precisely:
=>! says “we want this key-value pair”, so if the rhs returns the empty list you put in a scalar undef to maintain key/value parity
=>? says “I might not care about this key-value pair”, so if the rhs returns the empty list you gobble the left-hand side / abandon the pair entirely.
Does this make any sense?
Sam
--
Website: http://www.illuminated.co.uk/
Thread Next
-
Extend the fat comma to deal with undef
by Sam Kington