2017-09-06 12 views
-2

私は単純な "ファイルへの書き込み"をPerlで持っています。しかし、if文の中にファイルは書き込まれません。 if文の外側に書き出します。条件が常に満たされ、通常の印刷が行われる場合。どんな手掛かり?"ファイルへの書き込み"はif文の中では機能しません

open (FH, '>>', $files) or die $!; 

print FH "outside if, write to file"; 

if (condition){ 
    print FH "inside if, write to file"; 
    print "inside if, normal print"; 

}; 

出力はconditionprintを無効にするパッケージに機能することをtiesファイルハンドルFHで、

inside if, normal print 

ファイルの内容がObviousy

outside if, write to file 
+0

あなたはどのようにチェックします:ここで

はプロトタイプですか?また、スクリプトが実行されている間にファイルの内容をチェックしている場合は、ファイルハンドルを[閉じる](http://p3rl.org/close)することを忘れないでください。 – choroba

+6

実際のコードを表示してください。これがそうであれば 'if(condition)'( '$'はありません)ということもあります。これは '警告を使用する 'ことを意味します(確かに' use strict; 'もありません)。 。 – zdim

+0

投稿したコードを試してみました。問題がどこにあるかを把握できるように完全なコードを表示してください。 – Tim

答えて

6

です。

$files = $ARGV[0]; 
sub condition { tie *FH, 'print_disabler'; 1 } 
sub print_disabler::TIEHANDLE { bless {},shift } 
sub print_disabler::PRINT { return } 

open (FH, '>>', $files) or die $!; 

print FH "outside if, write to file"; 

if (condition){ 
    print FH "inside if, write to file"; 
    print "inside if, normal print"; 

}; 

$ perl condition.pl foo 
inside if, normal print 
$ cat foo 
outside if, write to file 
+1

非常に涼しいちょうど "明白"それはです:) – zdim

+0

私はこれを終わらせます –

関連する問題