What time? What happen?

  • use がしていること
# use strict; は内部的に以下のように展開される
BEGIN {
    require 'strict'
    strict->import();
}
  • BEGIN節, CHECK節
#!/usr/bin/perl
use strict;
use warnings;

use Perl6::Say;

say "When am I displayed";

BEGIN { say 1; }
CHECK { say 4; }
CHECK { say 3; }
BEGIN { say 2; }

# <実行結果>
# コンパイルフェーズが終了した後に,CHECK節が書かれている順とは逆順で実行されている事が分かる
# $ perl ./try.pl
# 1
# 2
# 3
# 4
# When am I displayed
  • BEGIN節, CHECK節, INIT節
#!/usr/bin/perl
use strict;
use warnings;

use Perl6::Say;

say "When am I displayed";

BEGIN { say 1; }
INIT  { say 5; }
CHECK { say 4; }
CHECK { say 3; }
INIT  { say 6; }
BEGIN { say 2; }

# <実行結果>
# INIT節は,CHECKブロックの後,ソースに書かれている順に実行されている事が分かる。
# $ perl ./try.pl
# 1
# 2
# 3
# 4
# 5
# 6
# When am I displayed
  • BEGIN節, CHECK節, INIT節,END節
#!/usr/bin/perl
use strict;
use warnings;

use Perl6::Say;

say "When am I displayed";

END   { say 8; }
BEGIN { say 1; }
INIT  { say 5; }
CHECK { say 4; }
CHECK { say 3; }
INIT  { say 6; }
BEGIN { say 2; }
END   { say 7; }

# <実行結果>
# END節は,プログラムの実行が終わってプログラムがexit終了する段階で,
# ソースに書いた順とは逆順で実行されている事が分かる。
# $ perl ./try.pl
# 1
# 2
# 3
# 4
# 5
# 6
# When am I displayed
# 7
# 8
  • 複数モジュールでのBIGIN節,INIT節の実行順番
# First.pm
package First;

BEGIN
{
    print __PACKAGE__ . ":BEGIN\n";
}

INIT
{
    print __PACKAGE__ . ":INIT\n";
}

1;

# Second.pm
package Second;

BEGIN
{
    print __PACKAGE__ . ":BEGIN\n";
}

INIT
{
    print __PACKAGE__ . ":INIT\n";
}

1;

# try.pl
#!/usr/bin/perl
use strict;
use warnings;

use Perl6::Say;

use First;
use Second;

say "hello";

# <実行結果>
# $ perl try.pl
# First:BEGIN
# Second:BEGIN
# First:INIT
# Second:INIT
# hello

参考:perlmod - Perl のモジュール (パッケージとシンボルテーブル)