Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^3: Parsing multiple lines based on a given String

by Marshall (Canon)
on Jun 22, 2016 at 22:07 UTC ( [id://1166318]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Parsing multiple lines based on a given String
in thread Parsing multiple lines based on a given String

There are a number of ways to implement this code.
One is shown below.
Basically, keep track of the last hostname found. When you find a valid ip, and that ip is the one that you are looking for, then that goes with the most previous hostname.
#!usr/bin/perl use warnings; use strict; my $file =<<END; object-group network HOSTNAME_1ST network-object host 10.1.1.1 object-group network HOSTNAME_2nd network-object host 10.3.1.1 object-group service WEB_TCP tcp port-object eq 80 END my $hostname; open my $fh, '<', \$file or die "unable to open read file $!"; while (my $line = <$fh>) { if (my ($name) = $line =~ /^object-group network (\w+)/) { $hostname = $name; # "last seen hostname" } my ($ip) = $line =~ /(\d+\.\d+\.\d+\.\d+)/; if (defined ($ip) and $ip eq '10.3.1.1') { print "ip $ip goes with host name $hostname\n"; } } __END__ ip 10.3.1.1 goes with host name HOSTNAME_2nd

Replies are listed 'Best First'.
Re^4: Parsing multiple lines based on a given String
by ArifS (Beadle) on Jun 27, 2016 at 15:23 UTC
    I tried to replace the following line-
    open my $fh, '<', \$file or die "unable to open read file $!";
    with -
    my $filename = 'file.txt'; open(my $fh, '<:encoding(UTF-8)', $filename) or die "Could not open file '$filename' $!";
    and it doesn't give an output or any error. Any clue? --------------------------------------------------------------- oh, never mind... had to use chomp. chomp($line);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1166318]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-04-19 10:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found