Search code examples
arraysperlmason

Printing array in perl mason


I am new to Perl Mason and I am trying to print an array. I tried several ways, explored the web but nothing seems to work.

I tried -

my $arr = getArray();
print "Array : $arr"; # prints "Array : ARRAY(0xcd421774)"
my $size = scalar $arr;
print "Size : $size"; # prints "size ARRAY(0xcd421774)"

I also tried to print the first element of the array

print "Element : $arr[0]"; # throws error "Global symbol "@arr" requires explicit package name at ..."

Solution

  • Your $arr is an array reference. You need to dereference it with the @{ … } operator: @{ $arr } or the shorthand @$arr.

    my $arr = getArray();
    print "Array : @$arr";
    my $size = scalar @$arr;
    print "Size : $size";
    

    To access one element: ${ $arr }[0] or the shorthands $$arr[0] or $arr->[0], of which the last form should be preferred.

    To learn more about Perl references, read perldoc perlreftut.