我有2个输出: -
7: ib1: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP>
9: bondib0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP>
Run Code Online (Sandbox Code Playgroud)
使用perl我想获得substr ib1和bondib0.目前,如果我设置
substr($line,3,3); this will return ib1
substr($line,3,7); this will return bondib0
Run Code Online (Sandbox Code Playgroud)
我想在上面有一个substr,怎么做?
像substr($ line,3,index($ line,":"));
请告诉我如何获得3和7个以上索引的动态值,因为值的长度不同.
你的使用方法substr,index应该工作.但是,还有另外两种方法可以做到这一点.
更容易的是使用正则表达式并进行模式匹配.
while (my $line = <DATA>) {
if ($line =~ m/: ([^:]+):/) {
print $1, "\n";
}
}
__DATA__
7: ib1: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP>
9: bondib0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP>
Run Code Online (Sandbox Code Playgroud)
这将匹配冒号:和空格上的字符串, and then capture everything that is not a colon, until it encounters another colon. See regex101.com for an explanation, and take a look at perlretut for a gentle introduction to regex.
An alternative would be to use split在冒号和空间上使用.那里只有两个.
while (my $line = <DATA>) {
( undef, my $interface ) = split /: /, $line;
print $interface;
}
__DATA__
7: ib1: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP>
9: bondib0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP>
Run Code Online (Sandbox Code Playgroud)
它会将弦打成碎片": ",丢弃第一部分,保存第二部分并丢弃其余部分.
然而,正则表达式解决方案更好.
| 归档时间: |
|
| 查看次数: |
34 次 |
| 最近记录: |