How do you add a method to an existing class in Perl 6?

后端 未结 4 1883
太阳男子
太阳男子 2021-02-19 04:40

The Int class has a method is_prime, so I figured, just for giggles, I\'d like to add some other methods to Int for some of my hobby projects that do n

4条回答
  •  深忆病人
    2021-02-19 05:29

    You can also simply call a sub like a method by including the & sygil:

    sub is-even(Int $n) { $n %% 2 }
    say 4.&is-even;  # True
    

    It's just syntactic sugar, of course, but I've done it a few times when it looked more readable than simply calling the sub.

    (I know you're “not looking for workarounds or alternate solutions”, but you posted some yourself, so I thought, why not?)

提交回复
热议问题