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

后端 未结 4 1994
名媛妹妹
名媛妹妹 2021-02-19 07:26

Here is the situation I am facing...

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

decode_json returns a reference. I am sure this is a

相关标签:
4条回答
  • 2021-02-19 08:00
    $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.

    0 讨论(0)
  • 2021-02-19 08:01

    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.

    0 讨论(0)
  • 2021-02-19 08:05

    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};
      # ...
    }
    

    Update

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

    0 讨论(0)
  • 2021-02-19 08:27

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

    my $length = $#{$perl_scalar} + 1;
    
    0 讨论(0)
提交回复
热议问题