Does Perl 6 have an equivalent to Python's update method on dictionary?

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}

And if you don't like either of those, roll your own...

sub infix:<Update>(%h , %u) { %h{ %u.keys } = %u.values }

my %hash  = Python => 2, Perl => 5;
my %u = Perl => 6 , Rust => 4.5 ;

%hash Update %u ;
say "After: %hash.perl()" ;    # After: {:Perl(6), :Python(2), :Rust(4.5)}

You can also augment the Global hash type;

augment class Hash {
    method update(%u) { self{ %u.keys } = %u.values }
}

%hash  = Python => 2, Perl => 5;
%u = Perl => 6 , Rust => 4.5 ;

%hash.update: %u ;
say "After: %hash.perl()" ;    # After: {:Perl(6), :Python(2), :Rust(4.5)}

..but, as this is perhaps the ultimate in action at a distance, you have to acknowledge that you know what you're doing through the indignity of placing use MONKEY-TYPING at the top of your program

Tags:

Raku