2011-08-01 8 views
2

これはなぜ存在するのですか?pwdと他の例の結果が異なっていますか?ここで何が起こっていますか?Perl -e Test Oddity?

[[email protected]:~/perltests]> cat testopensimple.pl 
#!/usr/bin/perl 

use strict; 
use warnings; 

# |<command> for writing 
# <command>| for reading 

testopen("| pwd"); 
testopen("pwd |"); 
testopen("| hostname"); 
testopen("| cd"); 
testopen("| sh"); 
testopen("| sleep 2"); 

sub testopen { 
     my $command = shift; 

     print "Exists: " . (-e $command ? "true" : "false") . "\n"; 
     print "testopen($command)\n"; 
     eval { 
       open(my $fh, $command) or die "$! [email protected]"; 
       my $data = join('', <$fh>); 
       close($fh) or die "$! [email protected]"; 
       print $data . "\n"; 
     }; 
     if ([email protected]) { 
       print [email protected] . "\n"; 
     } 
} 

[[email protected]:~/perltests]> perl testopensimple.pl 
Exists: true 
testopen(| pwd) 
/home/me/perltests 

Exists: true 
testopen(pwd |) 
/home/me/perltests 

Exists: false 
testopen(| hostname) 
unixbox1 

Exists: false 
testopen(| cd) 

Exists: false 
testopen(| sh) 

Exists: false 
testopen(| sleep 2) 

更新:

が、私はそれが内蔵の外部コマンド発行対シェルだと確信していません。外部のnetstatのようなコマンドで試してみてください。 pwdは、これまでパイプで存在チェックを真に戻してきた唯一のコマンドです。

アップデート2:私はやっていたテスト、「という名前のファイルのいくつかの繰り返しを通じて

| 「pwd」と「pwd |」結局作り出された。それは私が見ていることを説明しています。ありがとう。

答えて

3

-e '| pwd'は、現在のディレクトリに| pwdという名前のファイルがある場合にのみtrueを返します。

-e 'pwd |'は、現在のディレクトリにpwd |という名前のファイルがある場合にのみtrueを返します。

$ perl -E'say -e "| pwd" ? 1 : 0' 
0 

$ touch '| pwd' 

$ perl -E'say -e "| pwd" ? 1 : 0' 
1 

$ perl -E'say -e "pwd |" ? 1 : 0' 
0 

$ touch 'pwd |' 

$ perl -E'say -e "pwd |" ? 1 : 0' 
1 
+0

ここで起こったようです。私は<(read)と>(write)インジケータを使ってopen()を使っていくつかのテストを行っていました。 「pwd」と「pwd |」ファイル。ありがとう。 – user255205

+0

@ user255205:3つの引数を開いたままパイプを実行し、2番目の引数として '| - 'または ' - |'を指定することができます。 http://perldoc.perl.org/perlopentut.htmlの "fortune"の例を参照してください。 – ysth