开发者

Why is my Perl system command giving me a syntax error?

The Perl script that contains a Unix command to grep the ethernet NICs cannot be executed within the script! I have tried "qx" , $var and "system" but it does not seem to work!

The codes:

#!/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";

When executed the error "syntax error at ./ethercards.pl line 14, near "'ifconfig | awk '{" Execution of ./ethercards.pl aborted due开发者_Go百科 to compilation errors." shows up in the terminal.

Does anyone have any thoughts on this? Thanks!


Syntax highlighting also suggests that your system string is broken. Try

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


You are using the ' as the string delimiter but the ' also shows up in the string.

You then mistake the return value of system as the output of the command. When a command doesn't do what you expect, read its docs.

You're also doing a bit too much work on the command line. You're already in Perl, so avoid creating extra processes when you don't need to:

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

print "interfaces are @interfaces\n";

If you only want some interfaces, throw a grep in there:

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

print "interfaces are @interfaces\n";

I like to use the full path to executables so I know which one I'm getting. :)


If you need the output of your program, then write:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜