Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

perl

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.

like image 527
vkris Avatar asked May 04 '11 15:05

vkris


People also ask

How do you determine the number of elements in an array?

Just divide the number of allocated bytes by the number of bytes of the array's data type using sizeof() . int numArrElements = sizeof(myArray) / sizeof(int);

How do you find the size of an array?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.

How do you reference an array in SAS?

To refer to an array in a program statement, use an array reference. The ARRAY statement that defines the array must appear in the DATA step before any references to that array. An array definition is in effect only for the duration of the DATA step.


2 Answers

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.

like image 186
KARASZI István Avatar answered Oct 20 '22 13:10

KARASZI István


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

like image 21
Mark Gardner Avatar answered Oct 20 '22 15:10

Mark Gardner