Search code examples
perlfinalmoosemonkeypatching

How to make a method "final" in Perl?


I was wondering if it is possible to make sure a method in a class I make will NOT be monkey patched (Monkey patch). Can Moose achieve this?

Consider the following:

{
  package Foo;
  sub hello{print "HI"}
1;
}

package main;
sub Foo::hello {print "bye"}

Foo::hello()#bye

Solution

  • After a quick web research i found this thread on Perlmonks that states:

    As for declaring methods final, I'm not sure how you would do it without doing something really fancy to intercept all additions to the symbol table. (Can that even be done?).

    I would also assume that it is impossible.

    Using Moose you can apply Method Modifiers that allow you to define functions that must run before a function is called. I have not tried this but maybe you could define a function

    before "hello" => sub{ # check if hello has been tampered with
                       }
    

    I don't know exactly how to check it and if it even works, but it looks like it's worth a try!

    However I would add, that since perl is an interpreted language anyone who uses your package can view and edit the source, making any precaution circumventable.