class Variable
Object representation of a variable for use in traits
1 | Traits |
1.1 | trait is default |
1.2 | trait is dynamic |
1.3 | trait of |
2 | Methods |
2.1 | method name |
3 | Type Graph |
Variables have a wealth of compile-time information, but at runtime, accesses to a variable usually act on the value stored inside it, not the variable itself. The runtime class of a variable is Scalar.
Class Variable
holds the compile-time information that traits can use to introspect and manipulate variables.
Traits
trait is default
Sets the default value with which a variable is initialized, and to which it is reset when Nil is assigned to it. Trait arguments are evaluated at compile time. Closures won't do what you expect: they are stored as is and need to be called by hand.
my Int is default(42);say ; # OUTPUT: «42»= 5;say ; # OUTPUT: «5»# explicit reset:= Nil;say ; # OUTPUT: «42»
The trait is default
can be used also with subscripting things like arrays and hashes:
my is default( 'N/A' );[22].say; # OUTPUT: N/A= Nil;.say; # OUTPUT: [N/A][4].say; # OUTPUT: N/Amy is default( 'no-value-here' );<non-existent-key>.say; # OUTPUT: no-value-here<foo> = 'bar';<>.say; # OUTPUT: {foo => bar}<wrong-key>.say; # OUTPUT: no-value-here
trait is dynamic
multi sub trait_mod:<is>(Variable, :)
Marks a variable as dynamic, that is, accessible from inner dynamic scopes without being in an inner lexical scope.
sub introspect() { say $CALLER::x; } my $x is dynamic = 23; introspect; # OUTPUT: «23» { # not dynamic my $x; introspect() # dies with an exception of type X::Caller::NotDynamic }
The is dynamic
trait is a rather cumbersome way of creating and accessing dynamic variables. A much easier way is to use the * twigil
:
sub introspect() { say $*x; } my $*x = 23; introspect; # OUTPUT: «23» { # not dynamic my $x; introspect() # dies with an exception of type X::Dynamic::NotFound }
trait of
multi sub trait_mod:<of>(Mu , Mu )
Sets the type constraint of a container bound to a variable.
my of Int = 42;= "forty plus two";CATCH# OUTPUT: «X::TypeCheck::Assignment Type check failed in assignment to $i; expected Int but got Str ("forty plus two")»
You can use any value defined in compile time as a type constraint, including constants:
constant \T = Int;my of T = 42;
which would be equivalent to the previous definition.
Methods
method name
method name(Variable: str)
Returns the name of the variable, including the sigil.