2011-08-01 34 views
2

爲什麼這存在檢查返回pwd與其他示例不同的結果?這裏發生了什麼事?Perl -e測試奇怪?

[[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) 

更新:

我不相信它的內置VS外部命令發出一個外殼。嘗試使用外部的netstat等命令。 pwd是我迄今發現的唯一命令,它在管道存在檢查上返回true。

更新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

這似乎是在這裏發生的事情。我還用open()做了一些測試,使用<(讀)和>(寫)指示器,這些指示器又創建了「|」 pwd'和'pwd |'文件。謝謝。 – user255205

+0

@ user255205:您可以使用3-arg打開的管道,指定'| -'或' - |'作爲第二個參數。請參閱http://perldoc.perl.org/perlopentut.html中的「財富」示例 – ysth