モジュールが使用前にその内容を読み取れるように、実行時に必要なデータ ファイルを Perl モジュールにバンドルする「適切な」方法は何ですか?
簡単な例は、この辞書モジュールで、起動時に (単語、定義) ペアのリストを読み取る必要があります。
package Reference::Dictionary;
# TODO: This is the Dictionary, which needs to be populated from
# data-file BEFORE calling Lookup!
our %Dictionary;
sub new {
my $class = shift;
return bless {}, $class;
}
sub Lookup {
my ($self,$word) = @_;
return $Dictionary{$word};
}
1;
およびドライバー プログラム Main.pl:
use Reference::Dictionary;
my $dictionary = new Reference::Dictionary;
print $dictionary->Lookup("aardvark");
今、私のディレクトリ構造は次のようになります。
root/
Main.pl
Reference/
Dictionary.pm
Dictionary.txt
起動時に Dictionary.pm に Dictionary.txt をロードさせることができないようです。これを機能させるために、次のようないくつかの方法を試しました...
BEGIN ブロックの使用:
BEGIN { open(FP, '<', 'Dictionary.txt') or die "Can't open: $!\n"; while (<FP>) { chomp; my ($word, $def) = split(/,/); $Dictionary{$word} = $def; } close(FP); }
ダイスなし: Perl は cwd で Dictionary.txt を探します。これはメイン スクリプト ("Main.pl") のパスであり、モジュールのパスではないため、File Not Found と表示されます。
データの使用:
BEGIN { while (<DATA>) { chomp; my ($word, $def) = split(/,/); $Dictionary{$word} = $def; } close(DATA); }
そしてモジュールの最後に
__DATA__ aardvark,an animal which is definitely not an anteater abacus,an oldschool calculator ...
DATAが利用可能になる前に、コンパイル時に BEGIN が実行されるため、これも失敗します。
モジュール内のデータをハードコーディングする
our %Dictionary = ( aardvark => 'an animal which is definitely not an anteater', abacus => 'an oldschool calculator' ... );
動作しますが、明らかに保守できません。
同様の質問: Perl モジュールでデータ ファイルを配布するにはどうすればよいですか? しかし、それは、私がやろうとしている現在のスクリプトに関連するモジュールではなく、CPAN によってインストールされたモジュールを扱います。