25

Here is the situation I am facing...

$perl_scalar = decode_json( encode ('utf8',$line));

decode_json returns a reference. I am sure this is an array. How do I find the size of $perl_scalar?? As per Perl documentation, arrays are referenced using @name. Is there a workaround?

This reference consist of an array of hashes. I would like to get the number of hashes.

If I do length($perl_scalar), I get some number which does not match the number of elements in array.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vkris
  • 2,095
  • 7
  • 22
  • 30
  • Just for a straight array, the search engines are fond of *[Find size of an array in Perl](https://stackoverflow.com/questions/7406807)*. – Peter Mortensen Apr 27 '21 at 22:21

4 Answers4

41

That would be:

scalar(@{$perl_scalar});

You can get more information from perlreftut.

You can copy your referenced array to a normal one like this:

my @array = @{$perl_scalar};

But before that you should check whether the $perl_scalar is really referencing an array, with ref:

if (ref($perl_scalar) eq "ARRAY") {
  my @array = @{$perl_scalar};
  # ...
}

The length method cannot be used to calculate length of arrays. It's for getting the length of the strings.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KARASZI István
  • 30,900
  • 8
  • 101
  • 128
5

You can also use the last index of the array to calculate the number of elements in the array.

my $length = $#{$perl_scalar} + 1;
Thaha
  • 303
  • 3
  • 7
4
$num_of_hashes = @{$perl_scalar};

Since you're assigning to a scalar, the dereferenced array is evaluated in a scalar context to the number of elements.

If you need to force scalar context then do as KARASZI says and use the scalar function.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Gardner
  • 1,122
  • 10
  • 9
2

You can see the entire structure with Data::Dumper:

use Data::Dumper;
print Dumper $perl_scalar;

Data::Dumper is a standard module that is installed with Perl. For a complete list of all the standard pragmatics and modules, see perldoc perlmodlib.

shawnhcorey
  • 3,545
  • 1
  • 15
  • 17