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"; }
Red: [3] Green: [] Yellow: [0 2 5]
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.

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
    Thanks Eily. I am not familiar with the 'grep' feature, only loops and arrays structures. Is it possible to print strings for each output line "print "$search: @found\n";" ?. Thank you a lot!

      I'm sorry I did not get that question. I know that my code output is not exactly what you asked for, but the main logic is there. If you've already tried to adapt it to your needs, please show us your updated code, and what's missing for you to continue.