P N Jain
P N Jain

Reputation: 422

find nested array length in perl

I have deference array as given below -

"message": [
    {
      "abc": "",
      "xyz": "",
      "pqr": ""
    },
    {
      "abc": "",
      "xyz": "",
      "pqr": ""
    },
    {
      "abc": "",
      "xyz": "",
      "pqr": ""
    },
    {
     "abc": "",
      "xyz": "",
      "pqr": ""
    },
    {
     "abc": "",
      "xyz": "",
      "pqr": ""
    }
  ]

To find its length I tried following stuff but in each case I got answer as '1' instead of '5'.

1. say scalar @message;
2. my $attempt_length = @message;

It might be a very basic question but I am stuck here very badly. Please, help me in finding its length in Perl if anyone can. Thanks in advance.

Upvotes: 1

Views: 217

Answers (2)

SpiceMan
SpiceMan

Reputation: 74

In addition to the @$arrayref and @{ $arrayref } syntaxes ikegami already mentioned, I want to mention postfix dereferencing (available since perl v5.24, or with use experimental 'postderef' since perl v5.20)

my $num_of_elems = $arrayref->@*;         # implicit scalar context
my $num_of_elems = scalar $arrayref->@*;  # explicit scalar context

Upvotes: 0

ikegami
ikegami

Reputation: 385847

When you have a reference to a variable instead of a variable name, you simply replace the name in the syntax you want to use with a block that evaluate to the reference.

If you have the name of an array, you'd use the following to get its size:

@NAME             # In scalar context

If you have a reference to an array, you'd use the following to get its size:

@BLOCK            # In scalar context

So, if $messages contains a reference to an array, the following will get its size.

@{ $messages }    # In scalar context

You can omit the curlies if they contain a simple scalar ($NAME).

@$messages        # In scalar context

So,

use Cpanel::JSON::XS qw( decode_json );

my $json = do { local $/; <DATA> };
my $data = decode_json($json);
my $messages = $data->{message};
my $num_messages = @$messages;    # Or:  @{ $data->{message} }

__DATA__
{
  "message": [
    {
      "abc": "",
      "xyz": "",
      "pqr": ""
    },
    {
      "abc": "",
      "xyz": "",
      "pqr": ""
    },
    {
      "abc": "",
      "xyz": "",
      "pqr": ""
    },
    {
     "abc": "",
      "xyz": "",
      "pqr": ""
    },
    {
     "abc": "",
      "xyz": "",
      "pqr": ""
    }
  ]
}

See Perl Dereferencing Syntax.

Upvotes: 2

Related Questions