Question

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 ..."
Was it helpful?

Solution 2

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.

OTHER TIPS

I am not familiar with Perl Mason but it seems like getArray() does not return an array. It might be returning an array reference. I thought that's the reason why you assign it to a scalar variable $arr, not @arr;

You can confirm this using Data::Dumper

use Data::Dumper;
print Dumper $arr;

or ref.

if (ref($r) eq "ARRAY")

If it's indeed an array reference, you can access the first element like this:

$arr->[0];

Print the array like this:

print "Array : @$arr";

And get its size like this:

my $size = scalar @$arr;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top