Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't override the builtin print of Perl?

Tags:

perl

Following this example,

I tried to override print with my own:

BEGIN {*CORE::GLOBAL::print = sub {print 1};}
print 2;

But it turns out that it doesn't work,2 is still printed instead of 1.

Why?

like image 933
new_perl Avatar asked Sep 21 '11 06:09

new_perl


1 Answers

Because it has very special parsing rules that cannot be replicated by a normal function, the print operator cannot be overridden.

print "foo\n";
print { *STDOUT } "foo\n";

You can find out which operators can be overriden using prototype

>perl -E"say qq{$_: }, defined(prototype(qq{CORE::$_})) ? 'yes' : 'no' for @ARGV" print map time chr
print: no
map: no
time: yes
chr: yes

PS — You'd have an infinite loop if your code had actually overridden print.

like image 105
ikegami Avatar answered Nov 12 '22 21:11

ikegami