zakishah has asked for the wisdom of the Perl Monks concerning the following question:

How can i save the two IPs e.g. "10.10.10.10" in two different variable which appear after the second keyword "Static". My text file looks like this

0.0.0.0/0 *[Static/5] 02:30:27 > to 192.168.4.126 via em0.0 10.0.0.36/30 *[OSPF/10] 01:46:15, metric 2 > to 10.0.0.106 via em1.0 [BGP/170] 01:43:15, localpref 100, from 10.0.0.131 AS path: I 10.0.0.128/32 *[Static/5] 02:22:14 > to 10.0.0.110 via em2.0 [OSPF/10] 01:46:15, metric 3 > to 10.0.0.106 via em1.0

My code looks something like this but it does not seem to work

while(my $line = <DATA>) { if(/\bStatic\b/){ if(/\bStatic\b/){ my $IP = $line =~ /\d+\.\d+\.\d+\.\d+/; push(@IPS, $IP); } else { } } } print @IPS;
Thanks

Replies are listed 'Best First'.
Re: Finding specific keyword in Perl
by choroba (Cardinal) on Aug 21, 2012 at 14:35 UTC
    One possibility: count how many Static's you have seen. After the second one, capture all the IPs. You might need another flag to signal you are entering a new record for which you no longer want to capture them.
    #!/usr/bin/perl use warnings; use strict; my $static = 0; my @IPs; while (<DATA>) { push @IPs, $1 if /([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) +/ and $static == 2; $static++ if /Static/; }

      Thank you very much it really works but the problem is it is printing the ip's uptill the time the file is open. i need it to display ips only once which appears after second static. i dont want them to print multiple times

Re: Finding specific keyword in Perl
by tobyink (Canon) on Aug 21, 2012 at 14:52 UTC

    You need a few parentheses in there...

    my ($IP) = $line =~ /(\d+\.\d+\.\d+\.\d+)/;
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      Even better, use the Regexp::Common module. Far less chance of false matches.

      use Regexp::Common; my $IP_MATCH = $RE{net}{IPv4}{dec}; my ($IP) =~ $IP_MATCH;
      Bill
Re: Finding specific keyword in Perl
by Kenosis (Priest) on Aug 21, 2012 at 16:17 UTC

    Another option is to regex your file's slurped contents:

    use Modern::Perl; my $fileContents = <<END; 0.0.0.0/0 *[Static/5] 02:30:27 > to 192.168.4.126 via em0.0 10.0.0.36/30 *[OSPF/10] 01:46:15, metric 2 > to 10.0.0.106 via em1.0 [BGP/170] 01:43:15, localpref 100, from 10.0.0.131 AS path: I 10.0.0.128/32 *[Static/5] 02:22:14 > to 10.0.0.110 via em2.0 [OSPF/10] 01:46:15, metric 3 > to 10.0.0.106 via em1.0 END { local $/; open my $fh, '<', \$fileContents or die $!; my $data = <$fh>; my @IPs = $data =~ /Static.+Static.+> to ([\d.]+) via.+> to ([\d.] ++) via/s; say for @IPs; }

    Output:

    10.0.0.110 10.0.0.106