Tiago Peczenyj
Tiago Peczenyj

Reputation: 4623

Why can't I access lexical variables through a typeglob?

I don't understand why the example below fail (test 2). Why I cant access the variable bb from the *bb glob?

use Test::More tests => 4;

$aa = 1;
my $bb = 2;   # HERE!
local $cc = 3;
our $dd = 4;

is(${*aa}, 1, "$ \*aa should be 1");
is(${*bb}, 2, "$ \*bb (my) should be 2");
is(${*cc}, 3, "$ \*cc (local) should be 3");
is(${*dd}, 4, "$ \*dd (our) should be 4");

The output is

1..4
ok 1 - *aa should be 1
#   Failed test '*bb (my) should be 2'
#   at untitled line 10.
#          got: undef
#     expected: '2'
# Looks like you failed 1 test of 4.
not ok 2 - *bb (my) should be 2
ok 3 - *cc (local) should be 3
ok 4 - *dd (our) should be 4

Under perl 5.16.0

Thanks

Upvotes: 3

Views: 142

Answers (1)

choroba
choroba

Reputation: 242038

Lexical variables (those created with my) are not part of the symbol table, so they cannot be reached by globs. See also Of Symbol Tables and Globs.

Upvotes: 7

Related Questions