0

I am having trouble with my array of references which point to another array. Here's a snippet of my code:

# @bah is a local variable array that's been populated, @foo is also initialized as a global variable
$foo[9] = \@bah; 

# this works perfectly, printing the first element of the array @bah
print $foo[9][0]."\n"; 

# this does not work, nothing gets printed
foreach (@$foo[9]) {
    print $_."\n";
}

2 Answers 2

11

Always use strict; and use warnings;.

The @ dereference takes precedence, so @$foo[9] expects $foo to be an array reference and gets element 9 from that array. You want @{$foo[9]}. use strict would have alerted you that $foo was being used, not @foo.

For some easily memorizable rules for dereferencing, see http://perlmonks.org/?node=References+quick+reference.

Sign up to request clarification or add additional context in comments.

Comments

1

Like ysth says, you need to use braces to properly dereference $foo[9] into the array it points to.

You may however also want to be aware that using \@bah you are directly referencing the array. So that if change @bah later on, you will change $foo[9] as well:

my @bah = (1,2,3);
$foo[9] = \@bah;
@bah = ('a','b','c');
print qq(@{$foo[9]});

This will print a b c, and not 1 2 3.

To only copy the values from @bah, instead dereference $foo:

@{$foo[9]} = @bah;

Comments

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.