How to dereference hash references

后端 未结 3 707
难免孤独
难免孤独 2021-01-26 00:05

UPDATE: Everything I know about referencing/dereferencing came from here: http://www.thegeekstuff.com/2010/06/perl-array-reference-examples/

I\'m working with a library

相关标签:
3条回答
  • 2021-01-26 00:45
    my $hash_ref = @{$result};
    

    is the same as

    my @array = @{$result};
    my $hash_ref = @array;
    

    This forces the array to be evaluated in scalar context by the assignment operator, which causes it to evaluate as the number of items in the array, or 1.

    0 讨论(0)
  • 2021-01-26 01:01
    • We have a %hash.
    • To this, we have a hash reference $hashref = \%hash
    • This hashref is inside an array @array = ($hashref)
    • We get an array reference: $arrayref = \@array

    This is our result: $result = $arrayref. Not let's work backwards:

    • @result_array = @$result
    • $result_hashref = $result_array[0] or combined: $result_hashref = $result->[0]
    • %result_hash = %$result_hashref or combined: %result_hash = %{ $result->[0] } (note that these make a copy)
    • To get an element in the result hash, we can do
      • $result_hash{$key}
      • $result_hashref->{$key}
      • $result->[0]{$key}

    Note that $scalar = @{ $arrayref } does not work as you expect, because an array (which @{ … } is) returns the length of the array in scalar context. To force list context in an assignment, put the left hand side into parens: (…) = here_is_list_context (where is a list of zero or more lvalues).

    0 讨论(0)
  • 2021-01-26 01:05

    If @$result is an array then your LHS must be a list. Otherwise $hashref will be assigned the array size.

    my ($hash_ref) = @{ $result};
    print Dump($hash_ref));
    
    0 讨论(0)
提交回复
热议问题