Search code examples
perlreferencedereferenceperl-data-structures

The reason why typeglobs can be used as a reference in Perl


Sorry for may be not clear question, but I'm asking it, because I don't like to read something without understanding what I'm reading about.

Here is the snippet from the "Programming Perl":

Since the way in which you dereference something always indicates what sort of referent you’re looking for, a typeglob can be used the same way a reference can, despite the fact that a typeglob contains multiple referents of various types. So ${*main::foo} and ${\$main::foo} both access the same scalar variable, although the latter is more efficient.

For me this seems wrong, and that it would be right if it were this way:

you can use a typeglob instead of the scalar variable because reference is always a scalar and compiler knows what you need.

From the book's text, the reader can assume that a reference can be something other than a scalar variable (i.e. a scalar entry in the symbol table). Once I saw a warning: use of array as a reference is deprecated, so it appears to me that long ago this paragraph in the "Programming Perl" was meaningful, because references could be not just scalars, but in the new 4th edition it simply was not changed to comply with modern Perl.

I checked the errata page for this book but found nothing.

Is my assumption correct? If not, would be somebody so pleasant to explain, where I'm wrong.

Thank you in advance.


Solution

  • No. What it's saying is that unlike a normal reference, a typeglob contains multiple types of things at the same time. But the way in which you dereference it indicates which type of thing you want:

    use strict;
    use warnings;
    use 5.010;
    
    our $foo = 'scalar';
    our @foo = qw(array of strings);
    our %foo = (key => 'value');
    
    say ${ *foo };                  # prints "scalar"
    say ${ *foo }[0];               # prints "array"
    say ${ *foo }{key};             # prints "value"
    

    You don't need a special "typeglob dereferencing syntax" because the normal dereferencing syntax already indicates which slot of the typeglob you want to dereference.

    Note that this doesn't work with my variables, because lexical variables aren't associated with typeglobs.

    Sidenote: The "array as a reference" warning is not related to this. It refers to this syntax: @array->[0] (meaning the same as $array[0]). That was never intended to be valid syntax; it slipped into the Perl 5 parser by accident and was deprecated once Larry noticed.