Course of Raku / Advanced / Operators / Traits and pragmas 🆕 / Exercises / A custom trait
Solution: A custom trait
Here is a possible solution to the task.
Code
my %role;
multi sub trait_mod:<is>(Routine:D $r, :$role!) {
%role{$r.name} = $role;
}
sub login() is role('admin') { }
say %role<login>;🦋 You can find the source code in the file custom-trait.raku.
Output
adminComments
The trait is a
multi sub trait_mod:<is>whose named parameter:$role!triggers it foris role(...). Unlike a presence-only trait, this one receives the argument:is role('admin')binds'admin'to$role.The body stores that value under the subroutine’s name. Reading
%role<login>back afterwards givesadmin. (Traits run at compile time, so the entry is already there by the time the program runs.)