in reply to Get identical elements and index from 2 Arrays in Perl
That's one of the cases where it's easier (and actually required) to iterate over the indexes rather the elements themself. $#data is the index of the last element in the array @data:
my @ref = qw(Red Green Yellow); my @data = qw(Yellow Black Yellow Red White Yellow); for my $search (@ref) { my @found; for my $index (0..$#data) { if ($data[$index] eq $search) { push @found, $index; } } print "$search: [@found]\n"; }
This should give you most of what you need for your task. Are you familiar with grep? If so it can be used to get the @found array in one line rather than with a explicit loop.Red: [3] Green: [] Yellow: [0 2 5]
Also, while it's kind of acceptable to not use strict when testing, you should always avoid using one letter names for variables. Mostly for clarity, but also because some of them might have some hidden side effect / behaviour.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Get identical elements and index from 2 Arrays in Perl
by rebkirl (Acolyte) on May 27, 2019 at 14:29 UTC | |
by Eily (Monsignor) on May 27, 2019 at 14:51 UTC |