Search code examples
perljson

How do I determine the number of elements in an array reference?


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.


Solution

  • 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.