Perl 6

Perl 6: Poking classes

Perl 6 came with class keyword.
For example on declaring class:
class Animal {}

Setting attributes in the class:

class Animal {
    has $.species;
    has $.family;
    has $.kingdom;
}

It is boring if we can’t do anything with the attributes right? So let’s take a look at creating method.

class Animal {
    has $.species;
    has $.kingdom;
    has $.family;
    has $.aka;

    method sayInfo() {
        say "The animal normally called as, $!aka. It is $!species species.";
        say "It is also belong to $!kingdom kingdom, $!family family.";
    }
}
# instantiating

my $lion = Animal.new(species => 'P. leo', family => 'Felidae', kingdom => 'Animalia', aka => 'Lion');
$lion.sayInfo();

Well, thats it. I will cover much more topics in the future posts. Peace out.

BONUS

Subroutine dispatching or overloading.

#`(take note at the same subroutine name)

multi sub saySomething(Int $arg) {
    say "Hey, you inserted a number! $arg";
}

multi sub saySomething(Str $arg) {
    say "Hey, you inserted a string! $arg";
}

saySomething(20);   # => Hey, you inserted a number! 20
saySomething("hi");  # => Hey, you inserted a string! hi

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s