Camelia

How to get the index of specific element of an array in Perl 6 ?

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?

Note! This site is about Perl 6.
If you are looking for a solution for the current production version of Perl 5, please check out the Perl 5 tutorial.
Specifially there is a related article: How to get the index of specific element (value) of an array?.

In Perl 6 it is easy. There is a method called grep-index that will return the index of the matching element.

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:

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

index

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:

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)


The Perl 6 Tricks and Treats newsletter has been around for a while. If you are interested to get special notification when there is new content on this site, it is the best way to keep track:
Email:
Full name:
This is a newsletter temporarily running on my personal site (szabgab.com) using Mailman, till I implement an alternative system in Perl 6.
Gabor Szabo
Written by Gabor Szabo

Published on 2015-01-24



Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus
Suggest a change
Elapsed time: 4.0150176

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.
Email:
Name: