Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

How popular was/is monkeypatching in Perl?




It is possible to do so, but it stands out in a way such that most people aren't doing it using direct language features unless necessary. If you have `strict` and `warnings` enabled, which is recommended, then the interpreter can give runtime warnings or compile-time errors if you try to manipulate the symbol table or redefine a function. If you still want to use those on a case-by-case basis, you have to turn off those pragmas within a scope. So there are built-in ways the language discourages using them arbitrarily.

In tests, you can use monkeypatching as a quick way to mock, but typically, you use modules that wrap up the functionality and make it cleaner. The mocks get cleaned up on scope exit.

There are also more principled ways of having composable behavior, such as <https://metacpan.org/pod/Class::Method::Modifiers> (advice/method combination).

There is another approach that takes advantage of the variety of scoping approaches Perl has. If one uses `local`, it indicates the use of dynamic scope rather than the standard `my` lexical scope. This can be used for things like setting an environment variable temporarily and automatically reverting it when leaving the scope. But this is not common.


Very. I use `Test::MockModule` (not just in tests) or `Sub::Override` or `Class::Method::Modifiers` a lot, according to convention/style or as I see appropriate — but there are, of course, tons more ways to do it.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: