1
0

More than 3 years have passed since last update.

printのFILEHANDLE指定方法

Posted at

以下の書き方を見たことがなくて、どういう意味になるのか調べてみた。

print {*STDERR} "Hello\n";

というのも、標準エラー出力に書き込むだけならbarewordで特に問題ない認識だったので。

print STDERR "Hello\n";

If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead, in which case the LIST may not be omitted
https://perldoc.perl.org/functions/print.html

FILEHANDLEをブロックにすることで、以下のように複雑な表現も可能なんだそうで。

print { $files[$i] } "stuff\n";
print { $OK ? *STDOUT : *STDERR } "stuff\n";

ブロックで囲まないとダメ。サブルーチンの参照 \&func とかだと動かない。ブロックの中でサブルーチンを呼ぶのは問題なし。

こういうのも動く(あたりまえ)
print {&func} "Hello\n";

sub func {
    *STDERR;
}

条件によってファイルの出力先を変えたい場合、例えばログレベルみたいな実装をしたいときに使えるのかな。

1
0
6

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
1
0