DavidSzczesniak
12/13/2017 - 11:48 AM

Dereferencing

This returns the value from a reference point to the location. To do this, simply prefix a reference by the appropriate sigil based on what variable it's pointing to.

# Example to illustrate 

\!h # Scalar
my $var = 10; # original variable
my $r = \$var; # $r now has reference to $var
say "The value of $var is : $$r\n"; # prints value available at the location stored in $r.

\!h # Array
my @var = (1, 2, 3);
my $r = \@var;
say "Value of @var is : @$r\n";

\!h # Hash 
my %var = ('key1' => 10, 'key2' => 20);
my $r = \%var;
say "Value of %var is : %$r\n";

\!h # Check the variable type with 'ref'
my $var = 10;
my $r1 = \$var;
say "Reference type in r1 is ", ref($r1), "\n"; # Prints: Reference type in r1 is SCALAR
# The same goes for arrays and hashes

\!h # Access individual elements with the dereferencing arrow:
my @cards = qw(K Q J 2 3 4 5 6 7 8 9 10 A);
my $cards_ref = \@cards;
my $first_card = $cards_ref ->[0];
my $last_card = $cards_ref -> [-1];

# Alternatively, the uglier but maybe faster version of the above:
my $first_card = $$cards_ref[0];

# Example with a hash
my @english_colors = keys %$colors_ref; # access all the keys of a hash
my @spanish_colors = values %$colors_ref; # access all the values

# Access individual value of a hash
sub translate_to_spanish {
  my $color = shift;
  return $colors_ref -> {$color};
  # or return $$colors_ref{$color}
}

\!h # To slice an array reference: 
my @high_cards = @{$cards_ref}[0..2, -1];
# the curly braces aren't neccessary but do improve readability

# Slice a hash reference the same way
my @colors = qw(red blue green);
my @colores = @{$colors_ref}{@colors};