Scalar references
A reference is a scalar that remembers where another variable lives.
In this page:
Scalar references
The backslash operator makes a reference to a variable, so \$x points to $x. You follow, or dereference, the reference with an extra dollar sign as in $$ref, or with the arrow-free block form ${$ref}. Changing the value through the reference changes the original variable, because both name the same storage.
Note:
The ref function returns the type of a reference, such as SCALAR, ARRAY, HASH or CODE, and an empty string for a non-reference.
Example: Scalar references
use strict;
use warnings;
my $x = 10;
my $ref = \$x;
print "value through ref: $$ref\n";
$$ref = 20;
print "x is now $x\n";
${$ref} += 5;
print "x after += : $x\n";
print "ref type: ", ref($ref), "\n";
print "ref of plain value: '", ref($x), "'\n";
my $ref2 = $ref;
print "same target: ", ($ref == $ref2 ? "yes" : "no"), "\n";
# Output:
# value through ref: 10
# x is now 20
# x after += : 25
# ref type: SCALAR
# ref of plain value: ''
# same target: yes
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Printing a reference and expecting its value
- Forgetting the extra $ when dereferencing
- Assuming a reference is a copy of the data
Chapter Summary
- \$x makes a reference
- $$ref dereferences it
- Changes through a reference change the original
- ref returns the reference type
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: