0

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.

3
  • so you're trying to get the values from the other two arrays by index, based on the indexes found in @array_A? Commented Jul 17, 2016 at 18:26
  • @stevieb : Yes that's correct. Commented Jul 17, 2016 at 18:38
  • Don't you understand your my @index = … line or are you struggling with applying the result, (2, 5), to @array_B and @array_C? Commented Jul 17, 2016 at 18:40

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

The not-so-verbose solution would be my @a2_matches = @a2[ @indexes ]; and my @a3_matches = @a3[ @indexes ];. It makes use of array slices, but your solution is more educational.
@PerlDog that's what I was going for, as it was pretty apparent that the OP was doing a school project of some sort ;)
Yes, sure. I appreciate that and like your solution. I just added another approach.
@stevieb : Thanks much for your inputs.I'm able to fetch the values in array b and array C and write it to a file, like below: open my $fh, ">", "log.txt" or die "Cannot open log.txt: $!"; foreach (@array_B,@array_C){ print $fh "$_\n"; } close $fh; O/P: 12345 67891 12333 john jack joy How to write to a file in a following manner, 12345 john 67891 jack 12333 joy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.