A reference is a
The variable that reference points to can be:
Note:
;
- semicolons are mandatory while declaring, initializing, and executing statements in Perl.
We can declare a reference by adding backslash (\
) before a variable name.
$var1 = 69;
$ref_var1 = \$var1;
The following code snippet shows how we can declare and store variable references to another scalar type.
# Scalar string value reference$number = 1234;$integer_reference = \$number;print "Scalar Numeric reference: $integer_reference";# Scalar$string = "Hello World!";$string_reference = \$string;print "\nScalar String reference: $string_reference";# Array Reference@array = ('0', '1', '2', '3');$array_reference = \@array;print "\nScalar Array reference: $array_reference";# Hash Reference%hash = ('61'=>'a', '62'=>'b', '63'=>'c', '64'=>'d');$hash_reference = \%hash;print "\nScalar Hash reference: $hash_reference";
For the above example, we have learned how to reference a variable using a backslash (\
) . To access the content at that memory address, we will dereference the scalar variable.
Dereferencing is a way of accessing the stored memory of a variable using the same symbol of their datatype, e.g., @
for arrays, $
for variables, and %
for hashes.
Take a look at the following example that shows how to dereference a variable.
# Scalar string value reference$number = 1234;$integer_reference = \$number;# print "Scalar Numeric reference: $integer_reference";print $$integer_reference;# Scalar$string = "Hello World!";$string_reference = \$string;# print "\nScalar String reference: $string_reference";print "\n";print $$string_reference;# Array Reference@array = ('0', '1', '2', '3');$array_reference = \@array;# print "\nScalar Array reference: $array_reference";print "\n";print @$array_reference;# Hash Reference%hash = ('61'=>'a ', '62'=>'b ', '63'=>'c ', '64'=>'d ');$hash_reference = \%hash;# print "\nScalar Hash reference: $hash_reference";print "\n";print %$hash_reference;
Free Resources