Hi All,
My favorite variable is the associative array (hash). I finally updated
my keeper file on them.
If anyone is interested, here goes!
-T
Perl 6 Hashes (associative arrays):
References:
https://docs.perl6.org/language/subscripts#Basics
https://docs.perl6.org/type/Hash#:exists
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
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:
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
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 :bv 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)