Simplify the invocation of a common method

  • A+

I have a class like this:

class Foo {     method some-method(Str $name) { ... } } 

Simple usage:

my $foo =;  $foo.some-method("peter"); 

Since the "some-method" will be called quite frequently, I'd like to do something to allow users to use it like below:


I know FALLBACK will do the job, but it has been used for another method. I tried to define an infix operator:

sub infix:<%>(Foo $foo, $name) {     $foo.some-method($name); } 

The code below works, but the double quote is annoying.

$foo % "peter"; 

So is there any way to avoid the quote mark? Or any way to simplify the invocation?


As Curt Tilmes already pointed out, you could make your Foo object act as an Associative (or Hash):

class Foo {     method some-method(Str $name) { ... }     method AT-KEY(Str $name) { self.some-method($name) } } my $foo =; say $foo<peter>;   # same as $foo.some-method("peter") 

Of course, the AT-KEY method can be a multi, so you could play all sorts of tricks with that as well.

class Foo {     method some-method(Str $name) { "$name is ok" }     multi method AT-KEY("peter")   { "peter is special" }     multi method AT-KEY(Str $name) { self.some-method($name) } } my $foo =; say $foo<peter>;   # "peter is special" say $foo<joe>;     # "joe is ok" 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: