Making hacks file scoped like pragmas
作者:gugod 發佈於:The B::Hooks::OP::Check
-based hacks are global, which means that they effect all code being used. For crazy hacks like PerlX::Range
, it's better to make it localized like strict
. Here's how I make it so (briefly.)
use B::Hooks::EndOfScope;
sub import {
return if $^H{PerlXRange};
$^H &= 0x00020000;
$^H{PerlXRange} = 1;
add_flop_hook();
on_scope_end {
remove_flop_hook();
};
}
sub unimport {
remove_flop_hook();
$^H &= ~0x00020000;
delete $^H{PerlXRange};
}
There are two special variables, $^H
and %^H
. They are really documented in the perlvar
nicely, but not enough if you really want to play with it. Basically $^H
is a bit vector, the bit 0x00020000 tells perl to localize the value of %^H
for current package scope. In other words, the required/used code in other files will not see the value of $^H{PerlXRange}
.
Then in the flop hook callback, checking if $^H{PerlXRange}
exists first to tell if PerlX::Range
is in the scope.
The unimport
there is to let people saying no PerlX::Range
in their code to turn it off explicitly.