Variables & sigils

Dynamic variables $*

Full

Variables looked up through the call stack, not the lexical scope.

A variable with the * twigil ($*name) is dynamic: a called routine sees the caller's value, not one from where the routine was written. It's controlled action at a distance — for context like the current output handle or a request-scoped setting.

Visible down the call stack #

my $*greeting = "hi";
sub greet { say $*greeting }
greet();
Output
hi

greet never declares $*greeting, yet finds it — because the lookup walks the dynamic (caller) chain, not the lexical scope.

Rebinding for an inner scope #

Because the lookup follows the caller, redefining a dynamic variable in an inner block changes what calls made from that block see — and only those. When the block ends, the outer binding is back.

my $*g = "outer";
sub greet { say $*g }
{
    my $*g = "inner";
    greet();
}
greet();
Output
inner
outer

The first greet() runs while the inner $*g is in effect, so it prints inner; the second runs after the block, seeing outer again. (For an automatic restore without a new lexical scope, use temp.)

Notes #