1

Say I have a list of strings with possible repetitions. I am trying to find the list of sorted indices of this list that hold the unique entries in the list of strings.

E.g. Given:

my @string_list = ("hello", "world", "hello", "how", "are", "world");

The output with the list of indices would be: [0, 1, 3, 4] which correspond to the words "hello", "world", "how" and "are".

To do this, I can loop through the input list and keep track of the elements I have seen in a list in a dictionary that hold these indices, and use these indices later to obtain a list of unique items.

However, I was wondering if there are any other built-ins, functions or data-structures in Perl that facilitate this task and maybe avoid writing this in a loop.

Amelio Vazquez-Reina
  • 91,494
  • 132
  • 359
  • 564

1 Answers1

2

There is no built-in for such a concept as it isn't a very general thing to want to do. However it is only a couple of lines of code:

use strict;
use warnings;

my @string_list = qw( hello world hello how are world );

my @indices = do {
  my %seen;
  map { $seen{$string_list[$_]}++ ? () : ($_) } 0 .. $#string_list;
};

printf "[%s]\n", join ', ', @indices;

output

[0, 1, 3, 4]
Borodin
  • 126,100
  • 9
  • 70
  • 144