1. Perl
  2. Operators
  3. here

Dereference

A dereference is the opposite of creating reference to retrieve an entity from a reference.

Dereference array reference

Use "@{}" to dereference array reference.

my @array = @{$array_ref};

Please be aware that a new array is not created, but the entity is being retrieved.

If the inside of "@{}" is a simple variable, you can omit "{}".

my @array = @$array_ref;

This is an example program that dereference an array reference.

# Array reference
my $nums_ref = [1, 2, 3];

# Dereference
my @nums = @$nums_ref;

builtin functions that perform Perl array operations must pass an array, not an array reference. In this case, dereference it and pass it to the function.

my $nums = [1, 2, 3];

my $num = shift @$nums;

Dereference hash reference

Use "%{}" to dereference hash reference.

my %hash = %{$hash_ref};

Please be aware that a new hash is not created, but the entity is being retrieved.

If the inside of "%{}" is a simple variable, "{}" can be omitted.

my %hash = %$hash_ref;

This is an example program that dereference the hash reference.

# Hash reference
my $score_ref = {math => 19, english => 89};

# Dereference
my %score = %$score_ref;

Standard Perl hashing functions should pass a hash, not a hash reference. In this case, dereference it and pass it to the function.

my $score = {math => 89, english => 45};

my @keys = keys %$score;

Dereference a scalar variable reference

Use "${}" to dereference a scalar variable reference.

my $scalar = ${$scalar_ref};

If the inside of "${}" is a simple variable, "{}" can be omitted.

my $scalar = $$scalar_ref;

This is an example program that dereference the scalar reference.

# Scalar reference
my $string1 = "Hello";

my $string_ref = \$string;

# Dereference
my $string2 = $$string_ref;

Can I dereference other reference?

Subroutine Reference and Regular Expression Reference cannot be dereferenced ..

Related Informatrion