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

Hi,
I have a file in which each record is in the format :

12-APR-03 12:20:46.902801 IP 10.60.0.114.2684 > 10.60.0.3.110: . ack 3 +927995843 win 0


I need to parse out the source ip , sorce port , destination ip and port.
I have written the following code :

$file = 'testfile'; open(file_info,$file) or die "Can't open $file : $!"; while (<file_info>) { my ( $src_ip, $src_port ) = /IP\s+(\d+\.\d+\.\d+\.\d+)\/(\d+)/; my ( $dst_ip, $dst_port ) = />\s+(\d+\.\d+\.\d+\.\d+)\/(\d+)/; print "$src_ip $src_port $dst_ip $dst_port \n"; } close(file_info)

and this doesnt seem to work.
Please help.
Thanks, Himi

Replies are listed 'Best First'.
Re: Need help in perl regexp
by Skeeve (Parson) on Oct 05, 2007 at 09:59 UTC

    It simply "doesn't work" because your regexp doesn't match your data. Not "/" but "." seperates the port from the IP.

    while (<DATA>) { my ( $src_ip, $src_port ) = /IP\s+(\d+(?:\.\d+){3})\.(\d+)/; my ( $dst_ip, $dst_port ) = />\s+(\d+(?:\.\d+){3})\.(\d+)/; print "$src_ip $src_port $dst_ip $dst_port \n"; } __DATA__ 12-APR-03 12:20:46.902801 IP 10.60.0.114.2684 > 10.60.0.3.110: . ack 3 +927995843 win 0

    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: Need help in perl regexp
by moritz (Cardinal) on Oct 05, 2007 at 09:49 UTC
    "this doesnt seem to work" is not an accurate error description.

    My suggestion is to split at whitespaces, and takes those records that you want. If you want to get the port, you can split the records at dots.

    And please use <code>-Tags around your code and examples.

      I need to implement this using regexp.
      and im new to perl and do not know
      how to use regexp.
      please help
Re: Need help in perl regexp
by jeanluca (Deacon) on Oct 05, 2007 at 09:57 UTC
    I'm not sure this is the best way (maybe a perl expert can tell) but doing it your way, I made
    my $str = "12-APR-03 12:20:46.902801 IP 10.60.0.114.2684 > 10.60.0.3. +110: . ack 3927995843 win 0" ; if ( $str =~ /IP\s+(\d+\.\d+\.\d+\.\d+)\.(\d+)\s+>\s+(\d+\.\d+\.\d+\.\ +d+)\.(\d+)/ ) { print "matched: $1|$2|$3|$4"; }
    Cheers
    LuCa
Re: Need help in perl regexp
by svenXY (Deacon) on Oct 05, 2007 at 10:02 UTC
    Hi,
    my ($s_ip,$s_port,$d_ip,$d_port) = $line =~ /IP (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\.(\d+) > (\d{1,3}\.\d{ +1,3}\.\d{1,3}\.\d{1,3})\.(\d+)/;

    update: OK, ++others much faster ;-)
    Regards,
    svenXY
Re: Need help in perl regexp
by Himi (Novice) on Oct 05, 2007 at 10:11 UTC
    It worked!!!
    Thanks people... you all rock!!! :p
    Himi