Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a twigil in Perl6?

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?

like image 953
Zaid Avatar asked Jan 07 '16 11:01

Zaid


3 Answers

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....

like image 186
simbabque Avatar answered Oct 23 '22 11:10

simbabque


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

like image 10
Adam Taylor Avatar answered Oct 23 '22 13:10

Adam Taylor


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";
        }
    }
}
like image 9
serenesat Avatar answered Oct 23 '22 13:10

serenesat