Given an array like this:
my @levels = <TRACE DEBUG INFO WARNING ERROR FATAL>;
and give one of the names, e.g. 'DEBUG', how can we know which element is it?
In Perl 6 it is easy. There is a method called grep-index that will return the index of the matching element.
examples/array_element_index_grep.pl6
use v6; my @levels = <TRACE DEBUG INFO WARNING ERROR FATAL>; my $res = @levels.grep-index('DEBUG'); say $res; # 1 say $res.WHAT; # (List)
The WHAT method here revealed that the grep-index method actually returns a List. That's especialy usefule if the same element appears more than once. In that case grep-index will return the list of all the indices and if we want, we can access each individual index using square brackets:
examples/array_element_index_grep_duplicate.pl6
use v6; my @levels = <TRACE DEBUG INFO WARNING ERROR DEBUG FATAL>; my $res = @levels.grep-index('DEBUG'); say $res; # 1 5 say $res.WHAT; # (List) say $res.elems; # 2 say $res[0]; # 1 say $res[1]; # 5
I was a bit surprised to see that the plain index method converts the array into a string and returns the location of the value passed to it within that string:
examples/array_element_index.pl6
use v6; my @levels = <TRACE DEBUG INFO WARNING ERROR FATAL>; my $res = @levels.index('DEBUG'); say $res; # 6 say $res.WHAT; # (Int)
Published on 2015-01-24