šŸ¦‹64. What does gist do in Perl 6?

When you print an object, say, asĀ say $x, Perl 6 calls theĀ gistĀ method. This method is defined for all built-in types: for some of them, it calls theĀ StrĀ method, for some theĀ perlĀ method, for some types it makes the string representation somehow differently.

Let us see how you can use the method to create your own variant:

class X {
    has $.value;

    method gist {
        '[' ~ $!value ~ ']'
    }
}

my $x = X.new(value => 42);

say $x; # [42]
$x.say; # [42]

When you callĀ say, the program prints a number in square brackets:Ā [42].

Please notice that the interpolation inside double-quoted strings is using Str, notĀ gist. You can see it here:

say $x.Str; # X<140586830040512>
say "$x";   # X<140586830040512>

If you need a custom interpolation, redefine theĀ StrĀ method:

class X {
    has $.value;

    method gist {
        '[' ~ $!value ~ ']'
    }
    method Str {
        '"' ~ $!value ~ '"'
    }
}

my $x = X.new(value => 42);

say $x;     # [42]
$x.say;     # [42]

say $x.Str; # "42"
say "$x";   # "42"

Now, we got the desired behaviour.

2 thoughts on “šŸ¦‹64. What does gist do in Perl 6?

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s