ファイルハンドルを使用してプロセスから読み取る方法を学ぼうとしています。次のプログラムを使用して、「date」コマンドと参照からファイルハンドルを開くプログラムを作成しようとしました。
#!/usr/bin/perl
use warnings;
use diagnostics;
use strict;
open DATE, 'date|' or die "Cannot pipe from date: $!";
my $now;
while (1) {
print "Press any key: ";
chomp( my $result=<STDIN> );
$now = <DATE>;
print "\$now is: $now\n";
}
これは 1 回、または最初は機能しますが、後続の「ループ」は while (1) を介して行われ、2 回目には「$now の初期化されていない値」に関するエラーが発生します。さらに奇妙なことに、エラーは 2 番目のループの後に消えますが、「date」からのデータは $now 変数に取り込まれません。
これは、最初の実行後にファイルハンドルが閉じられていることを示している可能性があると思いますが、そうであるかどうかはわかりません。私はちょうど今 perl を学んでいます。これは簡単だと思いますが、この言語について十分な経験がありません。
誰でもこれについて私にガイダンスを提供できますか? ループを最初に実行した後、DATE ファイルハンドルが開いたままになることは期待できませんか?
この時点でのプログラムからの出力は次のとおりです。
$ perl ./test.perl
Press any key:
$now is: Fri Aug 17 15:00:27 EDT 2012
Press any key:
Use of uninitialized value $now in concatenation (.) or string at ./test.perl
line 16, <DATE> line 1 (#1)
(W uninitialized) An undefined value was used as if it were already
defined. It was interpreted as a "" or a 0, but maybe it was a mistake.
To suppress this warning assign a defined value to your variables.
To help you figure out what was undefined, perl will try to tell you the
name of the variable (if any) that was undefined. In some cases it cannot
do this, so it also tells you what operation you used the undefined value
in. Note, however, that perl optimizes your program and the operation
displayed in the warning may not necessarily appear literally in your
program. For example, "that $foo" is usually optimized into "that "
. $foo, and the warning will refer to the concatenation (.) operator,
even though there is no . in your program.
$now is:
Press any key:
$now is:
Press any key:
$now is:
Press any key:
$now is:
Press any key: ^C