2

I have two arrays, let's call them @a1 and @a2. What I'm trying to do is obtain elements from @a2 using the values in @a1 as indices. My current attempt doesn't work properly.

foreach (@a1) {
    print $a2[$_] . "at" . $_;
}

This only prints $_ but not $a2[$_].

I sense there is a trivial solution to this, but I just can't find it.

4
  • It works fine here: perl -E '@a1=(0,1,2); @a2=qw(a b c); for (@a1) {say $a2[$_]}' gives a, b and c.. Commented Jul 26, 2015 at 10:19
  • Interesting. The problem must be elsewhere then. Thank you. Commented Jul 26, 2015 at 10:23
  • use something like Data::Dumper to check what in a1 and a2 just before the foreach loop Commented Jul 26, 2015 at 11:21
  • for ( @a2[@a1] ) { say } Commented Jul 28, 2015 at 19:08

2 Answers 2

3

There is nothing wrong with the code you have. I have tested a small script and it works as expected. Asi i suggested in my comment, try using something like Data::Dumper to see whats in the arrays before the loop.

use strict;
use warnings;
use Data::Dumper;

my @a1 = (0..4);
my @a2 = ("a".."e");

print Dumper \@a1, \@a2;

foreach (@a1){
 print $a2[$_]." at ".$_."\n";
}

OUTPUT

$VAR1 = [
          0,
          1,
          2,
          3,
          4
        ];
$VAR2 = [
          'a',
          'b',
          'c',
          'd',
          'e'
        ];
a at 0
b at 1
c at 2
d at 3
e at 4
Sign up to request clarification or add additional context in comments.

1 Comment

Its handy for looking at whats in your variables. Just remember that when looking at an array or hash, it expects a reference to the array or hash, not the actual array or hash its self. so you need to pass it with the backslash.
0

there's no reason your code shouldn't work as long as the values of the first array are valid addresses in the second array. but if all you really want to do is just get the values and address of the second array, you could just do:

for my $i (0..$#a2) {
    print "$i: $a2[$i]","\n";
}

$#a2 is the last element address of the array.

1 Comment

The OP doesn't say if his array is for all elements. His array could be my @a1 = (4,6,8) as those might be key fields he is interested in. rather than every element in the array

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.