1

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.

1
  • Is message an array, or an array ref? If it is an array ref, then you want say scalar @$message. Commented Jan 6, 2020 at 9:46

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.