R.A. Epigonos et al.

[perl] スクリプトの動作に必要な個人情報をの設定ファイルを外部から読み出すにはIO::FileとJSONを使う

公開するスクリプトを書くときは、もしくはハードコーディングした個人情報を外部ファイルに保存するにはIO::FileとJSONの組み合わせで幸福実現。

ハードコーディングする例。これだとそのままでは公開できない。

$ cat webservice_client_skeleton.pl
#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $config = {
        password => "ppppppp",
        username => "uuuuuuu",
};
print Dumper $config;
exit;
__END__
$ perl webservice_client_skeleton.pl
$VAR1 = {
          'password' => 'ppppppp',
          'username' => 'uuuuuuu'
        };

コマンドライン引数で与える例。このままだと、psで確認するとパスワードとユーザ名が丸見え。

$ cat webservice_client_skeleton.pl
#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use Getopt::Long;

my %opts = ();
GetOptions(\%opts, 'username=s', 'password=s');

my $config = {
        password => $opts{password},
        username => $opts{username},
};
print Dumper $config;
sleep 20;
exit;
__END__
$ perl webservice_client_skeleton.pl --username uuuuuuuu --password pppppppp &
[1] 21819
$ $VAR1 = {
          'password' => 'pppppppp',
          'username' => 'uuuuuuuu'
        };

$ ps a | grep webservice_client_skeleton.pl
21819 pts/0    S      0:00 perl webservice_client_skeleton.pl --username uuuuuuuu --password pppppppp
$
[1]+  Done                    perl webservice_client_skeleton.pl --username uuuuuuuu --password pppppppp

外部ファイルにする例。コンフィグファイルのパーミッションを正しく設定していれば、それなりに守られる。

$ cat webservice_client_skeleton.pl
#
# Usage:
#
# $ perl webservice_client_skeleton.pl --config ~/.webservice.json
#
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use Getopt::Long;
use IO::File;
use JSON;

my %opts = ();
GetOptions(\%opts, 'config=s', 'id=i');

my $io = IO::File->new();
$io->open($opts{config}, 'r') or die $!;
my $config;
{
        local $/ = undef;
        $config = decode_json($io->getline);
}
$io->close;

$config->{id} = $opts{id} || 0;

main($config);
exit;

sub main
{
        my $config = shift;
        print Dumper $config;
}
__END__
$ perl webservice_client_skeleton.pl --config ~/.webservice.json
$VAR1 = {
          'password' => 'ppppppp',
          'username' => 'uuuuuuu',
          'id' => 0
        };

https://github.com/l/test/raw/master/perl/webservice_client_skeleton.plが自動的に読み込めませんでした。

リファレンス

  1. perl json - Google 検索
  2. JSON - モダンなPerl入門 - モダンなPerl入門
  3. perl 引数 オプション - Google 検索
  4. Perl スクリプトでのコマンドラインオプション処理
  5. Getopt::Long - perldoc.perl.org
  6. Perlメモ/IO::Fileモジュール - Walrus, Digit.

ソーシャルブックマーク

  1. はてなブックマーク
  2. Google Bookmarks
  3. del.icio.us

ChangeLog

  1. Posted: 2009-06-26T17:41:37+09:00
  2. Modified: 2009-06-26T17:41:37+09:00
  3. Generated: 2023-08-27T23:09:12+09:00