← Back to Perl Course | Chapter 6: References | Lesson 1 of 7

Scalar references

A reference is a scalar that remembers where another variable lives.

In this page:

  1. Scalar references

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

perl
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
Common Mistakes
  1. Printing a reference and expecting its value
  2. Forgetting the extra $ when dereferencing
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.