Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Thursday September 12, 2002
11:48 AM

References promote procastination

[ #7700 ]

In a previous journal entry, I reduced an if-elsif and Douglas Wilson showed another way to save a bit of typing. A few other people wrote to me with other sorts of solutions, which reminded me of another trick.

References can help you make decisions as late as possible, and when you really get you really chug from the Perl Kool-Aid you tend to delay decisions to the last possible moment. References can stand in place of named variables---a variable for variables, perhaps.

If I have a simple assignment to a scalar variable, Perl figures out where the data will live at compile time because that little chunk of memory has a name, and you use that name explicitly. Perl knows this at compile time.

my $foo = 'Hello Perl!'

If I assign to a reference, however, I can delay that choice until the last minute. It happens at runtime.

my $ref = $condition ? \$foo : \$bar;
$$ref = 'Hello Perl!';

In the previous example, I had a couple of variables in some of the conditions. Some of the if-elsif structure might be the same even though the parameters' names change. If I use references , I can reuse that structure possibly:

my( $ref1, $ref2 ) = ( \$param1, \$param2 );
 
if( $$ref1 > 5 and $$ref2 > 9 ) { ... }

I can also decide which parameters to check by populating an array elsewhere.

my( $ref1, $ref2 ) = @param_refs;

This, of course, looks suspiciously like the first line in a subroutine.

my( $ref1, $ref2 ) = @_;

You could pass the values directly to the subroutine, but then you have multiple copies of the same data floating around your program. You might not mind that, but if you also have to affect those data based on their value you need the references.