Translate

2008年8月12日火曜日

Dumpvalueモジュール

前回投稿したData::Dumperモジュールに引き続き
データ構造見るならデバッガのxコマンドで吐出す形式と
同じ方がいいなぁーという場合には、
use strict;
use warnings;
use Dumpvalue;

my $d = Dumpvalue->new();
my %hash;
$hash{a}{b} = "ab";
$hash{a}{c} = "ac";
$hash{b}{a} = "ba";
$hash{b}{c} = "bc";
$hash{c}{a} = "ca";
$hash{c}{b} = "cb";
$d->dumpValue(\%hash);

実行結果
'a' => HASH(0x276224)
'b' => 'ab'
'c' => 'ac'
'b' => HASH(0x27605c)
'a' => 'ba'
'c' => 'bc'
'c' => HASH(0x1853ef0)
'a' => 'ca'
'b' => 'cb'


例えば、大量に続くコードの途中にある変数の構造が知りたい時に
標準出力してしまうよりファイルに出力した方が何かと便利よさそうですよね。
『PERL HACKS』が言うには、
dumpValue()の出力先が標準出力であることを利用して
select関数を使って標準出力を一時的に変更してあげれば
ファイルへ出力もOKになるってことで…
use strict;
use warnings;
use Dumpvalue;

my $d = Dumpvalue->new();
my %hash;
$hash{a}{b} = "ab";
$hash{a}{c} = "ac";
$hash{b}{a} = "ba";
$hash{b}{c} = "bc";
$hash{c}{a} = "ca";
$hash{c}{b} = "cb";

open my $temp_fh, '>dump.txt';
my $old_fh = select($temp_fh); #select関数は、標準出力を変更し、現在の標準出力を返す。
$d->dumpValue(\%hash);
close $temp_fh;
select($old_fh); #標準出力を$old_fh(main::STDOUT)に戻す

で、ファイルに出力できますね。

0 件のコメント: