Skip to content

Commit b9d7227

Browse files
authored
add example of in-place editing of a hash key
also shows how to delete a hash key which seems to be missing
1 parent 98fa7f9 commit b9d7227

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

doc/Language/hashmap.pod6

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -462,9 +462,34 @@ specify that you would like read-write access to the values.
462462
my %answers = illuminatus => 23, hitchhikers => 42;
463463
for %answers.values -> $v is rw { $v += 10 };
464464
465-
It is not, however, possible to do in-place editing of hash keys, even in the
466-
case of object hashes.
465+
It is not possible directly to do in-place editing of hash keys, even in the
466+
case of object hashes; however, a key can be deleted and a new key/value pair
467+
added to achieve the same results. For example, given this hash:
467468
469+
=begin code
470+
my %h = a => 1, b => 2;
471+
for %h.keys.sort -> $k {
472+
# use sort to ease output comparisons
473+
print "$k => {%h{$k}}; ";
474+
}
475+
say ''; # OUTPUT: «a => 1; b => 2;»␤
476+
=end code
477+
478+
replace key 'b' with 'bb' but retain 'b's value as the new key's value:
479+
480+
=begin code
481+
for %h.keys -> $k {
482+
if $k eq 'b' {
483+
my $v = %h{$k};
484+
%h{$k}:delete;
485+
%h<bb> = $v;
486+
}
487+
}
488+
for %h.keys.sort -> $k {
489+
print "$k => {%h{$k}}; ";
490+
}
491+
say ''; # OUTPUT: «a => 1; bb => 2;»␤
492+
=end code
468493
469494
=end pod
470495

0 commit comments

Comments
 (0)