\ - Taking a Reference to an Existing Variable

Contents | Up | Prev | Next

# 10.2. \ - Taking a Reference to an Existing Variable

In Perl the backslash (`\`) is an operator that returns the reference to an existing variable. It can also return a dynamic reference to a constant.

Here is an example that uses a reference to update a sum:

    use strict;
    use warnings;

    my $sum = 0;

    sub update_sum
    {
        my $ref_to_sum = shift;
        foreach my $item (@_)
        {
            # The ${ ... } dereferences the variable
            ${$ref_to_sum} += $item;
        }
    }

    update_sum(\$sum, 5, 4, 9, 10, 11);
    update_sum(\$sum, 100, 80, 7, 24);

    print "\$sum is now ", $sum, "\n";

As can be seen, because the reference to `$sum` was used, its value changes throughout the program.

Contents | Up | Prev | Next