2010-09-09 17 views
13

的perlsub文档的Overriding Built-in Functions部分提供这Perl的内置插件无法在CORE :: GLOBAL被重写?

还有,当你想重写有时是适用的第二种方法的内置无处不在,而不考虑命名空间的边界。这是通过将一个子文件导入特殊命名空间CORE::GLOBAL::来实现的。

然后给出几个例子。在端部,但是,是

最后,一些内置插件(例如existsgrep)不能被重写。

什么是完整列表?

+0

我很高兴你问这个,因为我正要问自己,因为我必须为这本书写作。 :) – 2010-09-09 19:48:00

+0

@brian d foy我会把你的账单寄给你。 – 2010-09-09 19:49:01

+0

我会在啤酒券在一些Perl的事件赎回支付。 :)我正试图通过暴力来做到这一点,只是看看Perl的抱怨。我仍然可以这样做。 – 2010-09-09 20:00:46

回答

14

任何值,该值是在toke.c负可以被覆盖;所有其他人可能不会。您可以查看源代码here

例如,让我们来看看waitpid上线10396:

case 'w': 
     if (name[1] == 'a' && 
      name[2] == 'i' && 
      name[3] == 't' && 
      name[4] == 'p' && 
      name[5] == 'i' && 
      name[6] == 'd') 
     {          /* waitpid */ 
     return -KEY_waitpid; 
     } 

由于waitpid是负的,它可能会被改写。 grep怎么样?

 case 'r': 
      if (name[2] == 'e' && 
       name[3] == 'p') 
      {         /* grep  */ 
      return KEY_grep; 
      } 

这是积极的,所以它不能被覆盖。这意味着,以下关键字不能被重写:

chop, defined, delete, do, dump, each, else, elsif, eval, exists, for, foreach, format, glob, goto, grep, if, keys, last, local, m, map, my, next, no, package, pop, pos, print, printf, prototype, push, q, qq, qw, qx, redo, return, s, scalar, shift, sort, splice, split, study, sub, tie, tied, tr, undef, unless, unshift, untie, until, use, while, y

+1

OP中的链接包含一个模拟'glob'的特定示例。 – mob 2010-09-09 17:48:53

+3

该例通过将'glob'符号导出到调用包来实现,而不是替换'CORE :: GLOBAL ::'中的符号。 – friedo 2010-09-09 18:06:30

+0

必须有一些额外的魔术:'chop'和'splice'可以被模拟。我认为'shift','unshift','push'和'pop'也可以。 – mob 2010-09-09 18:11:28

5

prototype功能会告诉你,如果你可以覆盖CORE::功能。

这里是一个黑客一起试图让所有的功能,而无需键入它们:

#!/usr/bin/perl 

use strict; 
use warnings; 

open my $fh, "-|", "perldoc", "-u", "perlfunc" or die $!; 
my %seen; 
while (<$fh>) { 
    next unless my ($func) = /=item ([a-z]\w+)/; 
    next if $seen{$func}++; 

    my $prototype = prototype "CORE::$func"; 

    print "$func is ", defined $prototype ? "overiddable with $prototype " : 
     "not overiddable", "\n"; 
} 
+3

还有一些额外的魔法允许覆盖'do','require'和'glob'。请参阅'perlsub'了解(如果不是如何以及为什么)。 – mob 2010-09-09 18:03:18