Skip to content

Class and Attributes

Charlie Gonzalez edited this page Feb 16, 2016 · 5 revisions

How do you define a class in Perl 6?

You define a class by using the class keyword.

class BlackMage {

}

How do you define scalar and list attributes for a class ?

Attributes are declared with a 'has' keyword followed by the attribute name.Like Scalars and Arrays in Perl 6 a scalar attribute is defined with a '$' sigil and array attributes are defined with a '@' sigil both followed by an attribute name.As documented in Perl 6 Class Documentation the "." character in the attribute name is a twigil ( second sigil ) that will both declare an attribute and a read-only accessor method by the same name as the attribute.To declare an attribute without an accessor you can use the "!" twigil.

class BlackMage{
     has $.name;  # scalar attribute
     has @.magic; # list attribute
}

my $player1 = BlackMage.new( name => "Montblanc" , magic => [ "fire", "ice"]);

say $player1.perl;
say $player1.name;             # name accessor method.
say $player1.magic.join(', '); # magic accessor method

OUTPUT:

$ 
BlackMage.new(name => "Montblanc", magic => ["fire", "ice"])
Montblanc
fire, ice

How do you assign a default value to an attribute?

class BlackMage{
      has $.name = "Vivi Ornitier";
      has @.magic = ["fire","water","thunder"]
}

my $player1 = BlackMage.new( name => "Montblanc" , magic => [ "fire", "ice"]);
my $player2 = BlackMage.new();

say $player1.perl;
say $player2.perl;

OUTPUT:

$
BlackMage.new(name => "Montblanc", magic => ["fire", "ice"])
BlackMage.new(name => "Vivi Ornitier", magic => ["fire", "water", "thunder"])

How do you set an attribute accessor to read and write?

Use the "is rw" trait after defining the attribute.

class BlackMage{
    has $.name is rw = "Vivi Ornitier";                #scalar attribute
    has @.magic  is rw = ["fire", "water", "thunder" ]; #list attribute
    has $.head_gear = "Traveler cap";
    has $.torso_gear = "Traveler shirt";
    has $.leg_gear = "Traveler shorts";
    has $.accessory  = "Beginner pendant";
    
}

my $player1 = BlackMage.new( name => "Montblanc" , magic => [ "fire", "ice"]);


say $player1.perl;
say $player1.name;

$player1.name = "Charlie";  # Now I can assign a different value to name attribute.

say $player1.name;

OUTPUT:

$
BlackMage.new(name => "Montblanc", magic => ["fire", "ice"], head_gear => "Traveler cap", torso_gear => "Traveler shirt",
leg_gear => "Traveler shorts", accessory => "Beginner pendant")
Montblanc
Charlie