Документация
HTML CSS PHP PERL другое

Section 11.1.  Dereferencing

 
Previous
Table of Contents
Next

11.1. 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], "\n";

Note that the arrow syntax also interpolates correctly into strings, so the previous example would be better written:


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

Explicit dereferencing is prone to two specific mistakes, which can be hard to detect if use strict is not in effect. The first error is simply forgetting to wrap-and-prefix at all:

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

The second mistake is wrapping-and-prefixing correctly, but accidentally leaving off the reference variable's own sigil (i.e., the one inside the braces):

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

In both cases, the array accesses are accessing the variable @list_ref instead of the array referred to by the reference in $list_ref.

Of course, if you need to access more than one element of a container (i.e., to slice it) via a reference to that container, there's no choice except to use the wrap-and-prefix syntax:


    my ($from, $to) = @{$list_ref}[0, -1];

Attempting to use the arrow notation to achieve the same effect doesn't work:

    my ($from, $to) = $list_ref->[0, -1];

Because the access expression ($list_ref->[0, -1]) begins with a $ sigil, the square brackets are treated as a scalar context, so the list of indices is evaluated in scalar context, and the result is just the final index. So the previous example is equivalent to:

    my ($from, $to) = ($list_ref->[-1], undef);

    Previous
    Table of Contents
    Next
    © 2000- NIV