【问题标题】:Perl print more linesPerl 打印更多行
【发布时间】:2017-12-12 08:08:22
【问题描述】:

我是Perl 的新手,我想打印的不仅仅是第一个正则表达式匹配。 txt 文件包含 57 次 shutdown,使用下面的代码我只取回第一个匹配项,然后就停止了。

#!/usr/bin/perl
use strict;
use warnings;

use Path::Tiny;
use autodie;

my $dir = path("H:/Perl");

my $file = $dir->child("test.txt");

my $content = $file->slurp_utf8();

my $file_handle = $file->openr_utf8();

(my $test) = $content =~ m/^.+$(?=\s+shutdown)/mg;{
print "$test\n"; 
}

我尝试了while loop,但没有成功。感谢您的帮助。

编辑: 以下是一些示例数据:

interface port-channelxyc
description provdb002
shutdown
switchport access vlan 123
spanning-tree port type edge

interface port-channel456
description provdb002
switchport access vlan 32
spanning-tree port type edge

interface port-channel200
shutdown

我只回来了: '描述 provdb002' 然后它停止了,但我也想得到下一个:'interface port-channel200'等等......希望你明白我的意思。

【问题讨论】:

  • 你的正则表达式确实返回一个带有/g的列表;所以将它分配给一个数组:my @ary = $content =~ ...
  • 您能否提供一些示例数据以及所需的输出?冒着听起来很愚蠢的风险,文件肯定是utf8,因为那不是很常见吗?该模式的问题在于它会返回一个列表,但我不确定它是否会捕获正确的内容。
  • 请编辑您的问题并在此处添加数据。如果你把它放在评论中,就不可能知道换行符在哪里。
  • 如果你所有的文件确实都是这样,你就不需要slurp_utf8,就像@Sobrique 怀疑的那样,而是slurp(然后将你的匹配项分配给一个数组)。正则表达式确实需要一些讨论
  • 好的,您的示例输入 - 您想要的输出是什么?

标签: regex perl multiline


【解决方案1】:

好的,您的数据看起来像是用空行分隔的。

方便地,perl 非常容易地支持它,使用$/ 并将其设置为''

所以你可以像这样迭代你的文件:

#!/usr/bin/env perl
use strict;
use warnings;

local $/ = '';
while ( <> ) {
   my %this_int = m/([\w\-]+) ?(.*)/g; 

   if ( exists $this_int{'shutdown'} ) { 
       print  $this_int{'interface'}, " ", $this_int{'description'} // ''," is shut down\n";
   }
}

将打印您的示例数据:

port-channelxyc provdb002 is shut down
port-channel200  is shut down

【讨论】:

  • m/…()…()…/g 的结果直接分配给%hash 是个不错的主意。我会记住的。
猜你喜欢
  • 2016-06-13
  • 2020-02-29
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
  • 2016-07-11
相关资源
最近更新 更多