0

I need to create a multi-dimensional array which will be passed to a class.

Here is sample code where I can reference the array elements outside of the class, but once I create a class and pass the multi-dimensional array, I'm not able to reference it inside of the class.

Output:

My Array Value = 3

Can't use string ("1") as an ARRAY ref while "strict refs" in use at test.pl line 18.

package TestClass;
use strict;

sub new
{
    my $class = shift;
    my $self =
    {
        _array => shift
    };
    bless $self, $class;   
    return $self;
}

sub print
{
    my ($self) = @_;
    print "TestClass variable = " . @{$self->{_array}->[0]}[1] . "\n";
}

my @my_array = ();
push(@my_array, [1,2]);
push(@my_array, [3,4]);

print "My Array Value = " . @{@my_array->[1]}[0] . "\n";

my $class = new TestClass(@my_array);

$class->print;

1;

1 Answer 1

4

You're passing a list with two elements to your constructor, each element being one of the array refs you built.

I believe you wanted to pass an array reference containing the other two anonymous array references instead:

TestClass->new(\@my_array);

Your array de-referencing in @{@my_array->[1]}[0] is also a little odd. This is something use warnings; would've caught.

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

1 Comment

Agreed. $my_array[1][0] (or $self->{_array}[0][1]) seems easier to read.

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.