Perl Best Practices [Electronic resources]

Damian Conway

نسخه متنی -صفحه : 317/ 41
نمايش فراداده

3.3. Reference Variables

Mark variables that store references with a _ref suffix .

In Perl, you can't give a variable a specific type to ensure that it's able to store only particular kinds of values (integer, string, reference, and so on). That's usually not a problem, because Perl's automatic type conversions paper over most of the cracks very neatly[*].

[*] If it

is a problem for you, take a look at the Attribute::Types module on CPAN.

Except when it comes to references.

It's an all-too-common mistake to put a reference into a scalar, and then subsequently forget to use the all-important dereferencing arrow:

sub pad_str {
my ($text, $opts) = @_;
my $gap   = $opts{cols} - length $text;        # Oops! Should be: opts->{cols}
my $left  = $opts{centred} ? int($gap/2) : 0;  # Should be: opts->{centred}
my $right = $gap - $left;
return $SPACE x $left . $text . $SPACE x $right;
}

Of course, use strict qw( vars ) (see Chapter 18) is supposed to pick up precisely this transgression. And it usually will. Unless, of course, there also happens to be a valid %opts hash in the same scope.

You can minimize the chances of making this mistake in the first place by always appending the suffix _ref to any variable that is supposed to store a reference. Of course, naming reference variables this way doesn't

prevent this particular mistake, or even catch it for you when you do. But it does make the error much more visually obvious:

sub pad_str { my ($text, $opts_ref) = @_; my $gap = $opts_ref{cols} - length $text; my $left = $opts_ref{centred} ? int($gap/2) : 0; my $right = $gap - $left; return $SPACE x $left . $text . $SPACE x $right; }

If you adopt this coding practice[*], your eyes will soon come to expect an arrow after any occurrence of _ref, and the absence of such a dereferencer will become glaringly obvious.

[*]

You could also write a very short Perl script to detect and correct such mistakes:

#! /usr/bin/perl -w while (my $src_line = <>) { $src_line =~ s{ _ref \s* (?= [\{[(] ) }

# If _ref precedes opening bracket...
{_ref->}gxms;
# ...insert an arrow
print $src_line; }