I'm reading this fantastic introduction to Perl6 and came across a rather interesting term:
Note the
!
twigil means “this is private to the class”.class ScoreKeeper { has %!player-points; }
I know what sigils are in Perl5. But what's a twigil?
Is it just a fancy way to say that there are two sigils prepending the attribute/variable name?
The design documents S02 and S99 both talk about twigils. (Emphasis mine).
Ordinary sigils indicate normally scoped variables, either lexical or package scoped. Oddly scoped variables include a secondary sigil (a twigil) that indicates what kind of strange scoping the variable is subject to: [...]
So it is a secondary sigil or rather a second sigil. Declaring $*foo
will not declare $foo
.
my $*foo = 1;
say $foo;
This will yield Variable '$foo' is not declared at....
It seems to be related to variable scoping:
Twigils influence the scoping of a variable...
Twigil Scope ------ ---------------------------------------------- none Based only on declarator * Dynamic ! Attribute (class member) ? Compile-time variable . Method (not really a variable) < Index into match object (not really a variable) ^ Self-declared formal positional parameter : Self-declared formal named parameter = Pod variables ~ The sublanguage seen by the parser at this lexical spot
http://docs.raku.org/language/variables#Twigils
From the documentation on twigils:
Attributes are variables that exist per instance of a class. They may be directly accessed from within the class via !:
class Point {
has $.x;
has $.y;
method Str() {
"($!x, $!y)"
}
}
Note how the attributes are declared as
$.x
and$.y
but are still accessed via$!x
and$!y
. This is because in Perl 6 all attributes are private and can be directly accessed within the class by using$!attribute-name
. Perl 6 may automatically generate accessor methods for you though. For more details on objects, classes and their attributes see object orientation.
Public attributes have the .
twigil, private ones the !
twigil.
class YourClass {
has $!private;
has @.public;
# and with write accessor
has $.stuff is rw;
method do_something {
if self.can('bark') {
say "Something doggy";
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With