Skip to Content
Perl Best Practices
book

Perl Best Practices

by Damian Conway
July 2005
Intermediate to advanced
544 pages
13h 8m
English
O'Reilly Media, Inc.
Content preview from Perl Best Practices

Chapter 11. References

Pointers are like jumps, leading wildly from one part of the data structure to another. Their introduction into high-level languages has been a step backwards from which we may never recover

Charles Hoare

References in Perl are much safer than raw pointers (such as those available in C or C++). Perl references cannot be left dangling towards a scalar that has been garbage-collected, and they cannot be coerced into pretending that a hash is an array.

Semantically they're very robust, but sometimes their syntax lets them down, making code that uses references confusing or misleading. In certain configurations, they can also interfere with the garbage collector.

Symbolic references have far more problems. It's entirely possible for them to dangle, and they can easily be used to access the wrong type of referent. They also subvert the pre-eminence of lexically scoped variables. All in all, they're more trouble than they're worth.

Fortunately, every one of these problems can be avoided by following a small number of simple guidelines…

Dereferencing

Wherever possible, dereference with arrows.

Use the -> notation in preference to "circumfix" dereferencing. In other words, when you're accessing references to containers, use the arrow syntax:

print 'Searching from ', $list_ref->[0] ,  "\n",
      '            to ', $list_ref->[-1] , "\n";

This style results in much cleaner code than explicit wrap-and-prefix dereferencing:

print 'Searching from ', ${$list_ref}[0], "\n", ' to ', ${$list_ref}[-1], ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Perl Best Practices

Modern Perl Best Practices

Damian Conway
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 0596001738Supplemental ContentErrata