Define a routine that can be called using method syntax

sqrt can be called via function syntax:

 > sqrt 16 4 

It can also be called via method syntax:

 > 16.sqrt 4 

Is there a way to make custom routines invokable through method syntax?

For example, define sq :

 > sub sq(Int $n) { $n*$n } sub sq (Int $n) { #`(Sub|64042864) ... } > sq 4 16 

Is there a way to make it callable as a method? I.e.

 > 4.sq 
+8
perl6
source share
2 answers

Is there a way to make custom routines invokable through method syntax?

Yes, just use the syntax .& , As in:

 625.&sqrt.say # 25 

Invocant is passed as the first argument:

 sub sq { $^a² }; say 4.&sq 4.&sq.say # 16 

The only catch is that you need to use unspace if you want to break the chain of methods into these few lines:

 4.&sq\ .&sq.say; 
+9
source share

You can use the monkey to enter text Int . Expect that the optimizer is a guarantee, your will / boobs are compressed, and the world ends in general. The skill of the monkey is evil. Do not use it if you do not need to.

 use MONKEY-TYPING; augment class Int { method sq(Int:D $i:){ $i * $i } }; my Int $i = 4; say $i.sq; 

You can mix a role with an object. Note that the object is an object, not an Int class and a $i container.

 my $i = 4 but role :: { method sq(Int:D $i:){ $i * $i } }; say $i.sq; 

You can create a free floating method and use the method call operator .& .

 my method sq(Int:D $i:){ $i * $i }; my $i = 4; say $i.&sq; 

EDIT:

If you really want to break assumptions, you can even access private attributes.

 class Foo { has $!bar = 'meow'; }; use MONKEY-TYPING; augment class Foo { method baz { say $!bar } }; Foo.new.baz # OUTPUT«meow␤» 
+4
source share

All Articles