baba yaga
baba yaga

Reputation: 119

Perl script to check another array values depending on current array index

I'm working on a perl assignment, that has three arrays - @array_A, @array_B and array_C with some values in it, I grep for a string "CAT" on array A and fetching its indices too

my @index = grep { $@array_A[$_] =~ 'CAT' } 0..$#array_A;
    print "Index : @index\n";

Output: Index : 2 5

I have to take this as an input and check the value of other two arrays at indices 2 and 5 and print it to a file. Trick is the position of the string - "CAT" varies. (Index might be 5 , 7 and 9)

I'm not quite getting the logic here , looking for some help with the logic.

Upvotes: 0

Views: 124

Answers (1)

stevieb
stevieb

Reputation: 9296

Here's an overly verbose example of how to extract the values you want as to show what's happening, while hopefully leaving some room for you to have to further investigate. Note that it's idiomatic Perl to use regex delimiters when using =~. eg: $name =~ /steve/.

use warnings;
use strict;

my @a1 = qw(AT SAT CAT BAT MAT CAT SLAT);
my @a2 = qw(a b c d e f g);
my @a3 = qw(1 2 3 4 5 6 7);

# note the difference in the next line... no @ symbol...

my @indexes = grep { $a1[$_] =~ /CAT/ } 0..$#a1;

for my $index (@indexes){
    my $a2_value = $a2[$index];
    my $a3_value = $a3[$index];

    print "a1 index: $index\n" .
          "a2 value: $a2_value\n" .
          "a3 value: $a3_value\n" .
          "\n";
}

Output:

a1 index: 2
a2 value: c
a3 value: 3

a1 index: 5
a2 value: f
a3 value: 6

Upvotes: 3

Related Questions