Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl reference clarification needed

Tags:

reference

perl

Straight from https://perldoc.perl.org/perlref.html

I don't understand below

 $$hashref{"KEY"}   = "VALUE";       # CASE 0
 ${$hashref}{"KEY"} = "VALUE";       # CASE 1
 ${$hashref{"KEY"}} = "VALUE";       # CASE 2
 ${$hashref->{"KEY"}} = "VALUE";     # CASE 3

What is the difference between case 1 and 2?

I am thinking anything inside ${} is a pointer to some address so it's like

my $hashref = \%hash;

${$hashref}{"KEY"} is really $$hashref{"KEY"} and this is dereferencing \%hash and looking up it's "KEY"

${$hashref->{"KEY"}} .. I would think is.. ?? I thought the rule was the bind closest to the left so I thought this also became $$hashref->{"KEY"}. which is same as ${$hashref}{'KEY'}. Am I getting this wrong?

like image 891
J Kim Avatar asked Sep 18 '26 16:09

J Kim


1 Answers

Case 0 and 1 are equivalent, these you have understood correctly.

Case 2 is a bit subtle:

${$hashref{"KEY"}} = "VALUE";

First, this executes $hashref{"KEY"} which looks up the "KEY" in a hash variable called %hashref. Despite its name it is a hash, not a hash reference! This returns a value in that hash.

Next, we dereference that value in the hash as a scalar reference: ${ ... }.

Finally, we assign a "VALUE" to the scalar reference target.

Case 3 is similar, but actually uses a hash reference.

If we rewrite Case 2 and 3, their relation might be clearer:

{ # Case 2
  my %hash;
  ${ $hash{"KEY"} } = "VALUE";
}

{ # Case 3
  my %hash;
  my $hashref = \%hash;
  ${ $hashref->{"KEY"} } = "VALUE";
}

Additional remarks:

  • The ${ … } dereference operator does not bind closest to left, it contains the value that will be dereferenced. The $$foo form is a short form of the ${ … } dereference operator if the reference is a normal scalar variable, as opposed to a more complex expression. This is not only the case for scalar references but also array refs (@{ … } and @$foo) and hash refs (%{ … } and %$foo).

  • The sigil ($ % @) of a dereference operator is not the type of the reference, but depends on whether we are accessing one or more values in the reference target.

    When we access a single value in a hash %hash this looks like $hash{"KEY"}.

    When we access a single value in a $hashref, this looks like $hashref->{"KEY"} or ${$hashref}{"KEY"} or $$hashref{"KEY"}.

    Despite the $ there is no scalar reference here. The scalar dereference operator ${ … } is essentially a separate operator from the hash reference subscript operator ${ … }{ … }.

  • The expression $$foo->{"KEY"} features a scalar reference to a hash reference! Firs the scalar reference $foo is dereferenced $$foo to a hash ref, in which a value …->{"KEY"} is accessed.

like image 140
amon Avatar answered Sep 21 '26 07:09

amon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!