Why can't I use the value of a Perl variable to access the name of a lexical variable?

Why is this seal 42:

$answer = 42; $variable = "answer"; print ${$variable} . "\n"; 

but this is not so:

 my $answer = 42; my $variable = "answer"; print ${$variable} . "\n"; 
+6
variables perl metaprogramming lexical
source share
4 answers

Only package variables (the view indicated in your first example) can be targeted using symbolic links. There can be no lexical ( my ) variables, so your second example does not work.

See the excellent β€œCopy with Scoping” article on how two separate system variables work in Perl. And see. Also excellent. Why is it stupid to use the variable-name for why it's stupid. :)

+15
source share

Perl has two completely separate, but largely compatible variable systems, package variables, as in the first example, and lexical variables, as in the second. There are a few things that everyone can do, besides the other:

Package variables are the only ones that can be:

  • localized (with local )
  • used as the target for a symbolic link (the reason the second OP example is not working)
  • used as simple words (auxiliary definitions, file descriptors)
  • used with typeglobs (because this is what the character really is under the hood)

Lexical variables are the only ones that can be closed (used in lexical closure).

Using a string value will help you declare package variables with our , making the difference more clear.

There are several times when symbolic links are useful in Perl, most of which are centered around manipulating a symbol table (for example, writing your own import in a module, rather than using Exporter , monkey-fixing modules at run time, -programming tasks). These are all advanced topics.

For other tasks, there is usually a better way to do this, for example with a hash. The general rule is to always work under use warnings; use strict; use warnings; use strict; if you do not know that there is no other way but to disable a part of the pragma (for example, using no strict 'refs'; as small a scope as possible).

+6
source share

Symbolic links only work with package variables. The symbol table does not track lexical variables (this is all vocabulary :).

+5
source share

The problem is that you cannot use a symbolic link to refer to a lexical variable. In both examples, ${$variable} searches for $main::answer . In the first case, $answer is a global package and shortened for $main::answer , so the link finds it. In the second, $answer is a lexical variable and does not live in any package, so the link cannot find it.

More in perlref under the heading Symbolic links .

+4
source share

All Articles