Passing a scalar reference in Perl

user685275 picture user685275 · May 3, 2011 · Viewed 10.3k times · Source

I know that passing a scalar to a sub is actually passing the reference, but since I am new to perl I still did the following test:

#!/usr/bin/perl
$i = 2;
subr(\$i);
sub subr{
    print $_[0]."\n";
    print $$_[0]."\n";
}

I thought the first line is going to print an address and the second line is going to give be back the number, but the second one is a blank line. I was pointed by someone one else to do this: ${$_[0]} and it prints the number. But she didn't know the reason why without {} it is not working and why it is working with {}. So what has happened?

Answer

Ed Guiness picture Ed Guiness · May 3, 2011

It's because your second print statement is equivalent to doing this...

my $x = $$_; print $x[0];

When what you want is

my $x = $_[0]; print $$x;

In other words, the de-referencing occurs before the array subscript is evaluated.

When you add those curl-wurlies, it tells perl how to interpret the expression as you want it; it will evaluate $_[0] first, and then de-reference to get the value.