How can I emulate 'grep -B' functionality in Perl?

后端 未结 3 1029
梦谈多话
梦谈多话 2021-01-20 10:45

I have been searching for a solution that allows me to search the lines of an array, and if a string match is made, push that line and the 2 previous lines into an array. It

3条回答
  •  梦毁少年i
    2021-01-20 11:39

    A basic version of your subroutine. I assume you wanted to return the list when done with it. Untested.

    sub ipsearch {
        my $ip = shift;
        my @IPVSCONFIG = (); # no matches should be empty list, not undef
        my @buffer = ()      # to avoid undef warnings
        for (@RAWDATA) {
            push @buffer, $_;
            shift @buffer if @buffer > 3;
            if (/\W+virtual\s$ip\s/) {
                push @IPVSCONFIG, @buffer;
                @buffer = ();
            }
        }
        return @IPVSCONFIG;
    }
    

提交回复
热议问题