プロが教えるわが家の防犯対策術!

perl内のサブルーチンで処理された結果(htmlタグで構成されたもの)を別htmlファイルに出力したいです。

sub index {
print "Content-type:text/html; charset=utf-8\n\n";
&main;
exit;
}

上記cgiにアクセスすると、sub index内のサブルーチン(&main内で処理されたもの)が表示されます。

仮に以下のように処理すると、newfile.htmlの中に&mainとだけテキスト表示されます。

open (OUT,">newfile.html");
print(HFILE &main);
close (OUT);

&mainを展開した状態でhtml出力する方法を教えてください。
何卒よろしくお願いいたします。

質問者からの補足コメント

  • うーん・・・

    open (OUT,">newfile.html");
    print(OUT &main);
    close (OUT);

    HFILEではなくOUTでした。

      補足日時:2017/03/08 01:58

A 回答 (1件)

モジュールを使っていいなら方法4がおすすめ。



use strict;
use warnings;
use autodie;
use IO::Capture::Stdout;

sub main {
my $number = shift;
print "main function($number)\n";
}
my $file = 'hoge.txt';

# 方法1
{
local *STDOUT;
open STDOUT, '>', $file;
main(1);
close *STDOUT;
}

# 方法2
{
open my $fh, '>>', $file;
local *STDOUT = $fh;
main(2);
close $fh;
}

# 方法3 スカラー入出力を利用する
{
my $output;
open my $stdout, '>', \$output;
local *STDOUT = *$stdout;

main(3);
open my $fh, '>>', $file;
print {$fh} $output;
close $fh;
}

# 方法4 IO::Capture
my $capture_stdout = IO::Capture::Stdout->new;
$capture_stdout->start;
main(4);
$capture_stdout->stop;
{
open my $fh, '>>', $file;
print {$fh} $capture_stdout->read;
close $fh;

}

# 方法5 tie

---
$ perl foo.pl
$ cat hoge.txt
main function(1)
main function(2)
main function(3)
main function(4)
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!