为什么我的Perl系统命令给我一个语法错误?

时间:2010-09-23 07:20:42

标签: perl unix command

包含用于grep以太网NIC的Unix命令的Perl脚本无法在脚本中执行!我试过“qx”,$ var和“system”但它似乎没有用!

代码:

#!/usr/bin/perl

use warnings;
use strict;
use Term::ANSIColor;

print "\nYou are now in Showing Ethernet Cards!\n\n";

print "**************************\n";
print "|Ethernet Cards Available|\n";
print "**************************\n";

print "\nThe Ethernet Cards that are available are: "; 
my $ex = system ('ifconfig | awk '{print $1}' | egrep "eth|lo"');
print "$ex";

执行错误“./ethercards.pl第14行的语法错误,”ifconfig |附近awk'{“ 执行./ethercards.pl因编译错误而中止。“显示在终端中。

有没有人对此有任何想法?谢谢!

3 个答案:

答案 0 :(得分:4)

语法突出显示还表明您的系统字符串已损坏。试试

system ('ifconfig | awk \'{print $1}\' | egrep "eth|lo"');

答案 1 :(得分:4)

您使用'作为字符串分隔符,但'也会显示在字符串中。

然后将system的返回值误认为是命令的输出。当命令没有达到预期效果时,请阅读其文档。

您在命令行上也做了太多工作。您已经在Perl中,因此当您不需要时,请避免创建额外的进程:

my @interfaces = `/sbin/ifconfig` =~ m/^(\w+):/gm;

print "interfaces are @interfaces\n";

如果您只想要一些接口,请在其中抛出grep

my @interfaces = grep { /^(?:eth|lo)/ } `/sbin/ifconfig` =~ m/^(\w+):/gm;

print "interfaces are @interfaces\n";

我喜欢使用可执行文件的完整路径,所以我知道我得到了哪一个。 :)

答案 2 :(得分:0)

如果您需要程序的输出,请写下:

my $ex = qx!ifconfig | awk '{print \$1}' | egrep "eth|lo"!;
print "$ex";