Ninja’s Tip of the Day: Even More Incomprehencible Perl

This is a tip that any old hat perl developer will know, but some of you who have just started playing with perl, or maybe who have only used it for simple scripts, might not be aware of. It’s one of the perl features that you see in code much more often than you see in documentation, and the truth is I’m not sure what term to really use for it, but variable indirection or indirect referencing sound decent (if someone knows what the proper term for this feature is, shoot me an email). The best way to see how this works is to take a look at a sample program.

#!/usr/bin/perl
$foo = “Hello World!”;
$bar = “foo”;
print “$$bar\n”;

so, if you type this into your favorite text editor and give it a run, what do expect to see? You might be surprised to find out that the application prints out “Hello World!”. So what’s going on? let’s look at it like this. $($bar); You see here that basically all we are doing is evaluating what is inside of bar, and using that as the identifier, so we get foo.

Now, one could ask, and with perfect validity, when this is going to ever be useful. The truth is, there are really only a few cases when this feature is massively useful, and it generally is related to when you are writing an interpreter for another language, or in certain very tricky text processing cases. Like many things in perl, it can be abused and used to make code very ugly, but when you find you need it, it can save a lot of time and make the code much easier to understand.


About this entry