Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "Not an ARRAY reference" error?

Tags:

arrays

perl

I have this script

#!/usr/bin/perl

use strict;
use warnings;

use yy;

my $data = [
    ["aax", "ert", "ddd"],
    ["asx", "eer", "kkk"],
    ["xkk", "fff", "lll"],
    ["xxj", "vtt", "lle"],
    ];

use Test::More tests => 4;

is(yy::type1_to_type2(\$data, 'aax'), 'ert');
is(yy::type1_to_type3(\$data, 'asx'), 'kkk');
is(yy::type2_to_type3(\$data, 'fff'), 'lll');
is(yy::type3_to_type1(\$data, 'lle'), 'xxj');

which uses this module

package yy;

sub typeX_to_typeY {
    my ($x, $y, $data, $str) = @_;

    foreach (@$data) {
    if ($_->[$x - 1] eq $str) {
        return $_->[$y - 1];
    }
    }

    return;
}

sub type1_to_type2 { typeX_to_typeY(1, 2, @_) }
sub type1_to_type3 { typeX_to_typeY(1, 3, @_) }
sub type2_to_type1 { typeX_to_typeY(2, 1, @_) }
sub type2_to_type3 { typeX_to_typeY(2, 3, @_) }
sub type3_to_type1 { typeX_to_typeY(3, 1, @_) }
sub type3_to_type2 { typeX_to_typeY(3, 2, @_) }

1;

and gives this error

Not an ARRAY reference at yy.pm line 6.
# Looks like your test died before it could output anything.

The line it complains about is

foreach (@$data) {

Isn't this the way to pass an array reference?

What am I doing wrong?

like image 656
Sandra Schlichting Avatar asked Mar 14 '11 16:03

Sandra Schlichting


2 Answers

You are creating a reference to a reference as $data is already an array reference - firstly, it is a scalar and secondly you used square brackets to initialise its value. So, change your calls to use $data rather than \$data.

like image 164
a'r Avatar answered Oct 23 '22 13:10

a'r


$data = [] is a reference to array. By using \$data you create a reference to a scalar.
Change the code to be:

is(yy::type1_to_type2($data, 'aax'), 'ert');
...
like image 27
Eugene Yarmash Avatar answered Oct 23 '22 11:10

Eugene Yarmash