Perl: ファイル全体を一度に読む込む

以下がその方法。

my $code = do { local $/; <$in> };
  • 説明

グローバル変数「$/」は,入力レコードセパレータ。
これをローカル化すると,「$/」の値は undef となる。
「$/」の値が undef の場合,入力は分離されていない単一のレコードとして扱われる。

  • local $/; で $/ が undef になるのか確認
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use Encode;
use Perl6::Say;

{
    local $/;
    say '$/ is undef' if not defined $/;
}

# <実行結果>
# $/ is undef
  • おまけ

Perl6::Slurp モジュールを使用すると,最初の例は以下のように書ける。

use Perl6::Slurp;

my $code = slurp $in;

See Also