我试图使用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;
Run Code Online (Sandbox Code Playgroud)
使用"perl a.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.
Run Code Online (Sandbox Code Playgroud)
反引号内的单引号不是嵌套的,你需要反斜杠反斜杠:
my $a = `ip -f inet addr show eth0| grep -Po 'inet \\K[\\d.]+'`;
Run Code Online (Sandbox Code Playgroud)
使用$a一个词法变量是错误的,它可能会导致莫名其妙的错误时,排序在后面使用利用$a作为一个特殊的变量.使用更有意义的名称.
此外,grep通常不需要从Perl 调用,您可以匹配Perl本身的字符串:
my ($ip) = `ip -f inet addr show eth0` =~ /inet ([\d.]+)/;
Run Code Online (Sandbox Code Playgroud)
要么
my ($ip) = `ip -f inet addr show eth0` =~ /inet \K[\d.]+/g;
Run Code Online (Sandbox Code Playgroud)