πŸ“˜ Dynamic variables in Perl 6

The scope of dynamic variables is calculated at the moment when a variable is accessed. Thus, two or more calls of the same code may produce different results.

Dynamic variables are marked with the * twigil (a character clearly referencing a wildcard).

In the following example, the echo() function prints a dynamic variable $*var, which is not declared in the function, nor is it a global variable. It, nevertheless, can be resolved when used in other functions, even if they have their own instances of the variable with the same name.

sub alpha {
Β Β Β  my $*var = 'Alpha';
Β Β Β  echo();
}

sub beta {
Β Β Β  my $*var = 'Beta';
Β Β Β  echo();
}

sub echo() {
Β Β Β  say $*var;
}

alpha(); # Alpha
beta();Β  # Beta

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s