Search code examples
perlsyntaxscopeperl-moduleperl-data-structures

Perl "\my $var" why is the "my" escaped with a backslash?


I was looking at some sample code for making and removing file paths using File::Path.

http://perldoc.perl.org/File/Path.html

I can get the functions to work fine but I have had some difficulty getting the error messaging to work right. In the example for capturing error messages they use a \ before the my. What is the purpose of this \?

# Sample code from the link above
remove_tree( 'foo/bar', 'bar/rat', {error => \my $err} );  # why escape the my?!?!
if (@$err) {
    for my $diag (@$err) {
        my ($file, $message) = %$diag;
        if ($file eq '') {
            print "general error: $message\n";
        }
        else {
            print "problem unlinking $file: $message\n";
        }
    }
}
else {
    print "No error encountered\n";
}

I have never seen this before and I can't find an explanation anywhere. I tried removing the \ and I get a syntax error so clearly it is needed, but why?


Solution

  • No, my has higher precedence than \ in Perl, so it's the whole expression my $err which \ is being applied to. \ itself isn't really an escape; to quote http://perldoc.perl.org/perlref.html#Making-References :

    References can be created in several ways.

    1. By using the backslash operator on a variable, subroutine, or value. (This works much like the & (address-of) operator in C.) This typically creates another reference to a variable, because there's already a reference to the variable in the symbol table. But the symbol table reference might go away, and you'll still have the reference that the backslash returned.

    For example:

    my $scalarref = \$foo;
    

    makes $scalarref a reference to the existing scalar variable $foo. By contrast,

    my $scalarref = \my $foo;
    

    creates a new scalar variable $foo and makes $scalarref a reference to it, which can be more compact.