2013-05-06 142 views
1

我想运行此命令,但不是从命令行运行。我想运行文件,例如first.pl,它执行一些其他命令。例如,当我运行这个文件我想这样做:如何在perl中执行存储在文件中的命令

perl -ne "print qq{$1\n} if /^\s+ (\w+)/x" file 

它应该在这个文件中。我尝试这样的:

my $input = "input.txt"; 
my @listOfFiles = `perl -ne "print qq{$1\n} if /^\s+ (\w+)/x" $input`; 
print @listOfFiles; 

但它没有打印任何东西。感谢您的回答。

+1

,你为什么要跑Perl作为一个单独的命令,而不是直接将代码放入脚本中? – Barmar 2013-05-06 22:25:09

+0

我该怎么办? – 2013-05-07 10:37:44

回答

2

没有必要单独运行perl的命令,只是做你想做的事,主要的脚本:

open my $file, "input.txt"; 
my @listOfFiles; 
while (<$file>) { 
    if (/^\s+ (\w+)/x) { 
    push @listOfFiles, $1; 
    } 
} 
close $file; 
print "@listOfFiles"; 
3

始终使用use strict; use warnings;!你会得到

Unrecognized escape \s passed through 
Unrecognized escape \w passed through 
Use of uninitialized value $1 in concatenation (.) or string 

由于$1是除了期望$input。所以你需要恰当地逃避你的论点。假设你不是在Windows系统上,

use strict; 
use warnings; 

use String::ShellQuote qw(shell_quote); 

my $input = "input.txt"; 
my $cmd = shell_quote('perl', '-ne', 'print "$1\n" if /^\s+ (\w+)/x', $input); 
chomp(my @listOfFiles = `$cmd`); 
print "$_\n" for @listOfFiles; 
+2

......或者可以使用'open',这实际上是同样的事情:'use autodie;打开我的$ cmd,“ - |”,@command_with_args; chomp(my @listOfFiles = <$cmd>);关闭$ cmd;' – amon 2013-05-06 22:28:12

+0

@amon,的确,谢谢。 – ikegami 2013-05-06 22:38:55

+0

然后我有错误: '无法找到字符串终结符''“EOF在-e行1之前的任何地方。' – 2013-05-07 06:18:17

相关问题