Instead of
my %y = ( 'aa'=>"AA", 'bb'=> "BB", 'cc'=>"CC", 'dd'=>"DD" );
in the code below,
I find the following useful for filling an associative array (when
testing and I dont care about the contents)
my %y = <aa bb cc dd> Z=> 'AA'..*;
#{aa => AA, bb => AB, cc => AC, dd => AD}
But if the contents matter, how about,
my %y = <aa bb cc dd> Z=> <AA BB CC DD>;
#{aa => AA, bb => BB, cc => CC, dd => DD}
The 'Z' is the zip operator, the '=>' links a key to its value.
The ..* uses the power of perl6 to generate sequences from an initial
member.
Richard
On Wednesday, March 01, 2017 01:01 PM, Todd Chester wrote:
Hi All,
And it even gets more interesting.
It even works with Associative Arrays (Hashes), which I adore!
Interesting how associative arrays don't print in order that they
were entered into the array.
<code>
#!/usr/bin/perl6
my @x = ( "a", "b", "c", "d" );
print "loop of \@x\n";
for @x.kv -> $index, $value {
print " Line no. <" ~ ($index + 1) ~
"> has an index of <$index> and a value of <$value>\n"; }
print "\n";
my %y = ( 'aa'=>"AA", 'bb'=> "BB", 'cc'=>"CC", 'dd'=>"DD" );
print "loop of \%y\n";
for %y.kv -> $key, $value {
print " \%y has an key of <$key> and a value of <$value>\n"; }
print "\n";
</code>
./LoopIndexTest.pl6
loop of @x
Line no. <1> has an index of <0> and a value of <a>
Line no. <2> has an index of <1> and a value of <b>
Line no. <3> has an index of <2> and a value of <c>
Line no. <4> has an index of <3> and a value of <d>
loop of %y
%y has an key of <cc> and a value of <CC>
%y has an key of <dd> and a value of <DD>
%y has an key of <bb> and a value of <BB>
%y has an key of <aa> and a value of <AA>