In Python, if I update the dict
dictionary with another dict called u
(use Perl
as key), it will update the value:
>>> dict = {'Python':'2', 'Perl' : 5}
>>> u = {'Perl' : 6}
>>> dict.update(u)
>>> dict
{'Python': '2', 'Perl': 6}
but in Perl 6 :
> my %hash = 'Python' => 2, Perl => 5;
> my %u = Perl => 6
> %hash.append(%u)
{Perl => [5 6], Python => 2}
So, Does Perl 6 have an equivalent to Python's update method on dictionary?
The update() method inserts the specified items to the dictionary. The specified items can be a dictionary, or an iterable object with key value pairs.
You can use the ,
operator to do the update:
my %u = Perl => 6;
my %hash = 'Python' => 2, Perl => 5;
%hash = %hash, %u;
say %hash; # => {Perl => 6, Python => 2}
And of course you can shorten the updating line to
%hash ,= %u;
In Perl 6, one option is to use a hash slice:
my %u = (Perl => 6);
%hash{%u.keys} = %u.values;
Result:
{Perl => 6, Python => 2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With