On 2019-12-06 10:24, JJ Merelo wrote:
Please use the new URLs, those are deprecated, are no longer updated,
and might stop working without prior notice:
https://docs.raku.org/language/subscripts#Basics
https://docs.raku.org/type/Hash#:exists
Cheers
JJ
Hi JJ,
Good catch. Thank you!
I have refined the keeper to include your modifications
and have added how to access values inside and array
and how to add key/pairs to an existing hash. I also
correct the :bv adverbs typo
-T
Perl 6 Hashes (associative arrays):
References:
https://docs.raku.org/language/subscripts#Basics
https://docs.raku.org/type/Hash#___top
https://docs.raku.org/type/Hash#:exists
https://docs.raku.org/type/Hash#method_append
A hash "associates" a Name, called a "key" to a Value, called a "value"
You assign them as follows:
# use whatever is easiest on the eyes
my %h = a => "A", b => "B"; or
my %h = ( a => "A", b => "B" ); or
my %h = [ a => "A", b => "B" ];
{a => A, b => B}
say %h.keys
(b a)
say %h.values
(B A)
You read them as follows:
$v = %h<b>
B
When the key is a variable, your read them as follows
$k = "a"
$v = %h{$k}
A
To add or delete and element, see the sections below labeled
Adding a key/value pair:
Deleting a key/value pair:
Looping through a hash:
Note: hashes DO NOT loop in the order that they were entered into
the hash
for @x.kv -> $key, $value {do something};
For example:
my %h = a => "x", b=>"r", c=>"z";
for %h.kv -> $key, $value {say "key = $key value = $value"; }
key = c value = z
key = a value = x
key = b value = r
Array's of hashes:
To access values inside and array of hashes:
my @a; my %h = a=>"A", b=>"B"; push @a, %h;
Access:
$x = @a[0]{"a"} # Note: you need the quotes
modify:
@a[0]{"b"} = "BB"
How to use arrays of hashes:
my @a;
my %h1; my %h2;
%h1 = a => 0, b => 1, c => 2;
%h2 = a => 9, b => 8, c => 7;
push @a, {%h1};
push @a, {%h2};
say @a;
[{a => 0, b => 1, c => 2} {a => 0, b => 1, c => 2}]
for @a.kv -> $i, $h { say "$i\n" ~ "$h\n"; };
# Note: the ~ is to make it easier to read
# even though $h is address as $ it is a hash
0
a 0
b 1
c 2
1
a 9
b 8
c 7
Checking for the presence of a key/value:
my %h = a => "x", b=>"r", c=>"z";
if %h<c> { say "exists"; } else { say "DOES NOT exist"; }
DOES NOT exist
if %h<b> { say "exists"; } else { say "DOES NOT exist"; }
exists
Adding a key/value pair:
my %h = a => "x", b=>"r", c=>"z";
%h.append( 'd', "D" ) # note: you need the ''
{a => x, b => r, c => z, d => D}
Deleting a key/value pair:
Note: "delete" is called an "adverb" in this context
my %h = a => "x", b=>"r", c=>"z";
%h<b>:delete; say %h
{a => x, c => z}
Display a key/value pair (:p adverb):
my %h = a => "x", b=>"r", c=>"z";
say %h<a>:p;
a => x
say %h<a b>:p; # note: no comma between the a and the b
(a => x b => r)
Return the key and value with the :k and :v adverbs:
my %h = a => 1, b => 2;
say %h<a>:k;
a
say %h<a b>:k;
(a b)
say %h<a b>:v;
(1 2)
Empty <> return everything:
say %h<>:v;
(2 1)
say %h<>:k;
(b a)