3

I've learned a perl statement like:

*VAR = \0;

create a read-only $VAR in answer https://stackoverflow.com/a/35083240/2492255, I'm trying to find more documents to understand why $VAR is read-only in this case, but with no luck, could someone help to explain or point me to some documents on this topic?

vts
  • 871
  • 3
  • 10
  • 21
  • I've checked that doc, but still unclear about it, what's the difference between `*VAR = \0` and `*VAR = 0`? the later is writable. – vts Nov 07 '18 at 13:33
  • A good thing to query about, but just in case let me say this: you don't want to use this just so, in normal code. There are pragmas and modules for setting things to be read-only (constants). – zdim Nov 07 '18 at 17:49

1 Answers1

5

*VAR is the symbol table entry for the following:

  • $VAR
  • @VAR
  • %VAR
  • &VAR

(It also has a slot for a file handle, a directory handle, a format and more.)

Because they store a bunch of variables of different types, the symbol table entries are called "typeglobs", or "globs" for short.

Assigning a reference to a to a glob sets the slot of the appropriate type to the referenced variable. This means that assigning a reference to a scalar to *VAR sets *VAR{SCALAR}, the value returned by $VAR. Since you are passing a reference to a constant, $VAR returns that constant.


*VAR = *OTHER;, on the other hand, makes the left-hand side name an alias for the right-hand side name.

  • It makes $VAR equivalent to $OTHER.
  • It makes @VAR equivalent to @OTHER.
  • It makes %VAR equivalent to %OTHER.
  • It makes &VAR equivalent to &OTHER.
  • etc

*VAR = 0; is treated as *VAR = *{"0"}; which means *VAR = *0;. This means, among other things, that $VAR will return the current script's name (as $0 would).


Reference: Typeglobs and Filehandles

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • 1
    Trivia: Globs are weird because they're a type of variable (`*foo`) and a type of value that a scalar can contain (`$x = *foo;`). Everything else is one or the other. – ikegami Nov 07 '18 at 14:03