References are a cool programming language feature, but I am not so enamored with the way that Perl implements them. With Perl, you have to put the symbol that represents the data type next to the reference when you dereference it. For example, in the following code you need to use two dollar signs because $two is a reference to a variable, $one:
use strict;my $one = 1;
my $two = \$one;
print $$two;
So you have to use two dollar signs to deference the value. Now, in the next example, I have created a scenario where you have a reference, to a reference, to a reference to a subroutine. In the real world, I don't think there would ever have to be a reason to do something like this, but it illustrates why I find this to be a weird way of implementing this language feature.
use strict;sub printText
{
print "Testing....\n";
}my $x = \&printText;
&$x();
my $y = \$x;
&$$y();
my $z = \$y;&$$$z();
So, at the end, you wind up with three dollar signs and the ampersand in order to deference $z. My C is pretty rusty, but this makes more sense to me:
#includeint main(int argc, char **argv)
{
int w = 1;
int *x = &w;
int *y = x;
int *z = y;
printf("%d\n", *x);
printf("%d\n", *y);
printf("%d\n", *z);
return 0;
}
You initialize the variable w, then initalize the pointers x, y, z to memory addresses that ultimately link back to the variable w. When you dereference them in the code, the compiler knows to just chain them back to the data in the memory address for the integer w. You don't have to do *, ** and *** to deference. It just knows that that is a pointer that needs to be dereferenced to get the value that it points to. Since Z points to Y, which points to X, which points to the memory address of W, it knows that they are just pointers and to follow the trail back to W when you dereference the variable Z.
Pointers and references are similar enough that there isn't a good reason that I can think of that this syntactic sugar from C couldn't have been applied to Perl's references. I'm no expert, so enlighten me if there is a reason for it. It just seems to me that it would have made a lot more sense to newbies to make &$$$z() be &$z() instead. I could see the argument that it forces a programmer to keep track of the relationship of $z to the things that it points to, but in the event that someone is use multiple levels of references, this might cause a lot of headaches, so I don't see any real gain there.
Leave a comment