2014-10-20 129 views
0

Perl脚本从配置文件中读取url。在存储为URL = http://example.com的配置文件数据中。 我怎样才能得到网站名称。我试过如何从Perl脚本调用shell

open(my $fh, "cut -d= -f2 'webreader.conf'"); 

但它不起作用。

请帮忙!

+3

你正在传递一个shell命令作为文件路径... – m0skit0 2014-10-20 11:56:06

+2

个人而言,我会说'不'。没有太多的理由尝试在Perl中执行像'cut'这样的操作。 – Sobrique 2014-10-20 14:18:54

回答

5

你有阅读管-|后续内容是被分叉的命令指示,

open(my $fh, "-|", "cut -d= -f2 'webreader.conf'") or die $!; 

print <$fh>; # print output from command 

更好的方法是直接用perl的读取文件,

open(my $fh, "<", "webreader.conf") or die $!; 
while (<$fh>) { 
    chomp; 
    my @F = split /=/; 
    print @F > 1 ? "$F[1]\n" : "$_\n"; 
} 
+0

非常感谢!有用! – ayunt 2014-10-21 06:19:29

0

也许是这样的?

$ cat urls.txt 
URL=http://example.com 
URL=http://example2.com 
URL=http://exampleXXX.com 

$ ./urls.pl 
http://example.com 
http://example2.com 
http://exampleXXX.com 

$ cat urls.pl 
#!/usr/bin/perl 

$file='urls.txt'; 
open(X, $file) or die("Could not open file."); 

while (<X>) { 
    chomp; 
    s/URL=//g; 
    print "$_\n"; 
} 
close (X); 
+2

如果文件打开失败,则不报告'$!',如果打开[perldoc open](http://perldoc.perl.org/functions/open.html),则不打开三个参数,否'严格使用;使用警告;' – 2014-10-20 12:32:25

+1

除了@ Dr.Avalanche提到的问题外,你还应该使用词法文件句柄。 – dgw 2014-10-20 12:52:25