Perl Language Variables Scalar References


A reference is a scalar variable (one prefixed by $ ) which “refers to” some other data.

my $value     = "Hello";
my $reference = \$value;
print $value;     # => Hello
print $reference; # => SCALAR(0x2683310)

To get the referred-to data, you de-reference it.

say ${$reference};                  # Explicit prefix syntax
say $$reference;                    # The braces can be left out (confusing)

New postfix dereference syntax, available by default from v5.24

use v5.24;
say $reference->$*; # New postfix notation

This "de-referenced value" can then be changed like it was the original variable.

${$reference} =~ s/Hello/World/;
print ${$reference};  # => World
print $value;         # => World

A reference is always truthy – even if the value it refers to is falsy (like 0 or "").

You may want a Scalar Reference If:

  • You want to pass a string to a function, and have it modify that string for you without it being a return value.

  • You wish to explicitly avoid Perl implicitly copying the contents of a large string at some point in your function passing ( especially relevant on older Perls without copy-on-write strings )

  • You wish to disambiguate string-like values with specific meaning, from strings that convey content, for example:

    • Disambiguate a file name from file content
    • Disambiguate returned content from a returned error string
  • You wish to implement a lightweight inside out object model, where objects handed to calling code don't carry user visible metadata:

    our %objects;
    my $next_id = 0;
    sub new { 
       my $object_id = $next_id++;
       $objects{ $object_id } = { ... }; # Assign data for object
       my $ref = \$object_id;
       return bless( $ref, "MyClass" );