"Why does this work?"
See CORE.
"What's the difference between CORE::GLOBAL::Caller and CORE::Caller."
The difference between CORE::GLOBAL::foo and CORE::foo is thus: The Perl built-in foo() function is "just an alias" for CORE::GLOBAL::foo(). The default implementation of CORE::GLOBAL::foo() is CORE::foo(). You can override CORE::GLOBAL::foo() (and thus the built-in foo() because that's "just an alias"), but you cannot override CORE::foo().
That's the concept anyway. The actual implementation details are far weirder. CORE:: for example is not just a package, but a part of Perl's syntax - a prefix you can add to a Perl keyword to indicate that you do not want to use an overridden CORE::GLOBAL::foo(). You cannot take references to all of the CORE:: and CORE::GLOBAL:: functions, only some of them (though each major release of Perl is improving in this regard).
"Elaboration why one thought BEGIN was needed, and why in fact it isn't"
It is necessary to have performed at least one override of CORE::GLOBAL::caller() before the line containing caller is compiled. If you're using stringy eval, then your line containing caller is probably compiled quite late.
But going back to my example:
use v5.12;
# This is basically a dummy override that must be performed early
# on so that Perl knows we'll be overriding CORE::GLOBAL::caller
# later...
#
BEGIN { *CORE::GLOBAL::caller = sub { CORE::caller(@_) } };
sub foo {
say scalar caller;
}
sub bar {
local *CORE::GLOBAL::caller = sub { 'xxxx' };
foo();
}
foo();
bar();
This outputs "main" then "xxxx". Commenting out the BEGIN block, it outputs "main" then "main" - not the desired effect. (Tested on Perl 5.12.5, 5.14.3, and 5.18.0.)
"why are things so slow when it is used?"
Because after the first time an override happens, any subsequent uses of caller() get compiled into an entersub op rather than a caller op. That is, they incur the full penalty of a sub call.
Compare:
$ perl -MO=Concise -E'BEGIN { *DUMMY::GLOBAL::caller = sub {} }; calle
+r()'
4 <@> leave[1 ref] vKP/REFC ->(end)
1 <0> enter ->2
2 <;> nextstate(main 49 -e:1) v:%,{,2048 ->3
3 <0> caller[t1] v* ->4
-e syntax OK
$ perl -MO=Concise -E'BEGIN { *CORE::GLOBAL::caller = sub {} }; caller
+()'
6 <@> leave[1 ref] vKP/REFC ->(end)
1 <0> enter ->2
2 <;> nextstate(main 49 -e:1) v:%,{,2048 ->3
5 <1> entersub[t3] vKS/TARG,1 ->6
- <1> ex-list K ->5
3 <0> pushmark s ->4
- <1> ex-rv2cv sK ->-
4 <#> gv[*CORE::GLOBAL::caller] s ->5
-e syntax OK
use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
|