Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: [Perl6] Slurpy array of named arguments?

by TheDamian (Priest)
on Dec 05, 2016 at 19:24 UTC ( #1177273=note: print w/replies, xml ) Need Help??


in reply to [Perl6] Slurpy array of named arguments?

The problem is that, in the argument list of a sub or method, any key => 'value' pair with an unquoted key is always treated as a named argument. So any such argument it is always routed into the slurpy hash, and never into the slurpy array.

The simplest solution is to quote the key of each pair, in which case they will be treated as positional arguments and will be routed into the slurpy array.

Of course, each such positional pair will be a single Pair object (not a flattened list of key, value) so you will end up with an array of pairs, not an array of alternating keys and values. That means you'll need to unpack them differently in the for loop.

Putting all that together, we get:

class testing { method newhash(*%args) { for %args.kv -> $k, $v { say "Hash Key $k => Value $v"; } } method newarray(*@args) { for @args».kv -> [$k, $v] { say "Array Key $k => Value $v"; } } } my $x = testing.newhash(a => 1, b => 2); # Messes with specified +order my $y = testing.newarray('c' => 3, 'd' => 4); # Looks okay, and work +s

If you simply must have unquoted keys, then you'll need to pass an explicit list of them (in parens), because the "unquoted-means-named" magic only applies at the outermost level (known as the "comma level") of the argument list. So, with the rewritten newarray method above, the following would also work:

my $y = testing.newarray((c => 3, d => 4)); # Looks okay, and works

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1177273]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2019-10-16 04:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?