Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: [Perl6] Slurpy array of named arguments?

by TheDamian (Vicar)
on Dec 05, 2016 at 19:24 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1177273]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-24 01:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found