Front page | perl.perl6.users |
Postings from April 2021
slurpy hash signatures
Thread Next
From:
Joseph Brenner
Date:
April 18, 2021 19:00
Subject:
slurpy hash signatures
Message ID:
CAFfgvXVaNtv1aRdmvQ+OxdM2UTC+88d3t7d-sWJnLNtdpYoBgg@mail.gmail.com
Before I get started here, a small point about defining hashes.
There are various ways that work:
my %h1 = ( 'ha' => 1, 'ho' => 2, 'hum' => 3 );
my %h2 = ( ha => 1, ho => 2, hum => 3 );
my %h3 = ha => 1, ho => 2, hum => 3;
my %h4 = 'ha' => 1, 'ho' => 2, 'hum' => 3;
say join(' ',
%h1{'ho'}, %h2{'ho'}, %h3{'ho'}, %h4{'ho'}
);
# Output: 2 2 2 2
Of course, when you're accessing the hash value, the key *does* need
to be quoted (unlike in perl), And because of this, I keep
thinking I need to quote keys (as in %h1 or %h4), though really
the pair operator does implicit quoting on the left (so %h2
and %h3 work and would usually be preferred).
By the way, I do know about this idiom:
say join(' ',
%h1<ho>, %h2<ho>, %h3<ho>, %h4<ho>
);
# Output: 2 2 2 2
Now, on to my main point...
I was wondering what sub signature invocation gives you behavior like
the standard "new" method, which takes a series of named arguments:
I see in Mu.pm6 there's this:
multi method new(*%attrinit) {
And here in an article by Elizabeth Mattijsen I see:
https://opensource.com/article/18/9/signatures-perl-6
If you want to catch any (other) named arguments, you can use a
so-called "slurpy hash." Just like the slurpy array, it is
indicated with an asterisk before a hash:
sub slurp-nameds(*%nameds) {
say "Received: " ~ join ", ", sort keys %nameds;
}
slurp-nameds(foo => 42, bar => 666); # Received: bar, foo
I find that if I very carefully imitate that in every detail, it
works fine:
sub genius(*%fried) { say %fried };
genius( ha => 1, ho => 2, hum => 3 );
## Output: {ha => 1, ho => 2, hum => 3}
But as I mentioned earlier, I often quote keys without thinking
about it:
genius( 'ha' => 1, 'ho' => 2, 'hum' => 3 );
## Error: Too many positionals passed; expected 0 arguments but got 3
So: when passing pairs to a sub, quoting the key causes
things to barf, and the messaging is seriously LTA.
(The pair operator is being demoted to a fat comma?)
Incidently, the "slurpy hash" is discussed in the docs, where
they're called "slurpy named arguments". That's under "Slurpy
parameters" here https://docs.raku.org/type/Signature
Elizabeth's examples are clearer, I think.
Thread Next
-
slurpy hash signatures
by Joseph Brenner