On 02/28/2017 01:20 PM, ToddAndMargo wrote:
Hi All,
There are times when I want to know th4e index of an array
when I am in a "for @array" loop. I can do it with a
variable outside the for loop and increment it, but
I would line to know know if there is a way to incorporate
it in the loop command.
This is my long winded way of doing it in Perl 5:
while (my ($Index, $Element) = each ( @Sorted_List ) ) { do something }
Many thanks,
-T
Hi All,
Thank you all!
Made me look up "kv":
https://docs.perl6.org/routine/kv
Returns an interleaved sequence of indexes and values. For example
<a b c>.kv; # (0 a 1 b 2 c)
I will be copying this down in my list of examples. Note that
I made the point that Perl starts counting at zero not one.
-T
<code>
$ cat ./LoopIndexTest.pl6
#!/usr/bin/perl6
my @x = ( "a", "b", "c", "d" );
for @x.kv -> $index, $value {
print " Line no. <" ~ ($index + 1) ~
"> has an index of <$index> and a value of <$value>\n"; }
</code>
$ ./LoopIndexTest.pl6
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>