LoginSignup
0
0

More than 5 years have passed since last update.

【Perl】簡易的にprintを標準出力に流さないようにする

Last updated at Posted at 2014-12-03

事始め

標準出力へログを出力するかしないかのメソッドを定義したのはいいけど、
内部で利用している別の人が作った関数が勝手に print するから完全にログの出力を制御できない。

printのリダイレクト先を変えれば良いわけだけどその場合の手っ取り早い方法について。

実際のコード

tie を利用して一時的に print をリダイレクトします。

test.pl
#/usr/bin/perl

use strict;
use warnings;

# ここから標準出力停止.
my $stopOutput = 1; # フラグが1なら標準出力停止.
{
    # 標準出力を停止させる.
    my $stopOutput = ($stopOutput==1) ? tie local *STDOUT, 'StopOutput' : (0);
    print "aaa\n";
}
# ここまで標準出力停止.

print "bbb\n";

# 標準出力を停止させる為のクラスを定義.
package StopOutput;
sub TIEHANDLE { my $class = shift; my @lines; bless \@lines, $class; }
sub PRINT {}

結果

test.pl
$ perl test.pl
bbb
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0