Perlに予約語ってあるのだろうか?

ソースコード解析ツールを見ていると、各言語の予約語の定義という
ものがあり、そういや Perl予約語ってなんだろうって思った。


予約語の定義とは Wikipediaによると

予約語(よやくご)とは、プログラミング言語において字句的には識別子(変数名、関数名、クラス名など)
としてのルールを満たしているにもかかわらず、識別子として使えない字句要素。

という意味のようです。


C言語だと

   % cat test.c
   #include <stdio.h>
   void struct (void)
   {
        printf("hello world");
   }
   % gcc test.c
   test.c:3: error: expected ‘{’ before ‘(’ token
   test.c:3: error: two or more data types in declaration specifiers

こんなのはできないし、


Javascriptだと

   % cat test.js
   function function () {
       console.log("Hello world");
   }
   function();
   % node test.js
   /Users/syohei/junk/gomi/test.js:1
   ction function (
           ^^^^^^^^

    node.js:116
            throw e; // process.nextTick error, or 'error' event on first tick
            ^
    SyntaxError: Unexpected token function
        at Module._compile (module.js:369:25)
        at Object..js (module.js:380:10)
        at Module.load (module.js:306:31)
        at Function._load (module.js:272:10)
        at Array.<anonymous> (module.js:393:10)
    at EventEmitter._tickCallback (node.js:108:26)

こんなのはできない。


でも Perlだと

#!perl
use strict;
use warnings;

sub sub {
    print "My name is sub\n";
}

sub my {
    print "My name is my\n";
}

sub __END__ {
    print "My name is __END__\n";
}

## 名前空間が必要
main::sub;
main::my;
main::__END__(); # 括弧が必要


これが実行できてしまう.

   % perl test.pl
   My name is sub
   My name is my
   My name is __END__

Wikipediaの定義からすると subとか myは予約語ではない
ということになる。

Perlだと予約語というかキーワードはソースコードの 'regen/keywords.pl'と
いうファイルに書かれている。250個以上もの単語が並んでいるわけだけど、
予約語となるとかなり限定されそうな感じですね。


いろいろ調べてみたところ、予約語らしきものは
BEGIN、END、INIT、CHECKでしょうか。

#!perl
use strict;
use warnings;

sub BEGIN {
    print "I'm BEGIN\n";
}

main::BEGIN();

実行すると以下の結果となりました。

   % perl test2.pl
   I'm BEGIN
   Undefined subroutine &main::BEGIN called at test2.pl line 9.

定義でエラーが出るわけじゃないけど、そんなものないと
言われてしまう。普通の BEGINブロックとして扱われて
しまっています。


このあたりがちょっと特殊な扱いということですかね。

最後に

Perl予約語に関して気になることを示しました。
Perlはキーワードは多いのかもしれないけど、予約語と呼べるものは
ほとんどないっぽいですね。そのキーワードも定義済み関数と
呼べるものが大半を占めてるので、あんまりそういうのには
縛られてないのかなと思いました。