用于从ip命令获取inet的Perl脚本



我正在尝试使用ip命令获取inet,它在cmd提示符下运行良好,但如果我将其添加到perl脚本中,它不会按预期执行。脚本如下:-

ip.pl
use strict;
my $a = `ip -f inet addr show eth0| grep -Po 'inet K[d.]+'`;
chomp($a);
print $a;

使用"perla.pl"执行以上操作只返回"ip-f inet-addr show eth0|grep-Po'inet\K[\d.]+'"返回inet值。如何使用perl脚本执行它?

打开警告以获得提示:

Unrecognized escape K passed through at ./1.pl line 5.
Unrecognized escape d passed through at ./1.pl line 5.

反斜杠中的单引号没有嵌套,您需要反斜杠:

my $a = `ip -f inet addr show eth0| grep -Po 'inet \K[\d.]+'`;

$a用于词法变量是错误的,当稍后使用将$a用作特殊变量的排序时,可能会导致奇怪的错误。使用更有意义的名称。

此外,通常不需要从Perl调用grep,您可以在Perl中匹配字符串:

my ($ip) = `ip -f inet addr show eth0` =~ /inet ([d.]+)/;

my ($ip) = `ip -f inet addr show eth0` =~ /inet K[d.]+/g;

最新更新