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

use strict; my $cmd="netstat >>C:\\perl-program\\test2\\netstat_ouput.txt"; system($cmd); my $file_name="netstat_ouput.txt"; my $pattern='WXP-DPBG8BS\s*:\s*(\d?\d?\d?\d?\d?)'; open(FH,"$file_name") or die "Could not able to open the file !"; while(<FH>) { my $line=$_; #print "$_\n"; if ($line=~m/$pattern/) { print "$line\n"; my @list=split $pattern,$line; print "Match is found ->!\n"; our @array=split ':',@list; foreach my $port(@array) { print "Port found:$port\n"; #print "Test\n"; } } else { print "No Match\n"; } } <c> =========================== netstat_output.txt ===========================<c> Proto Local Address Foreign Address State TCP WXP-DPBG8BS:1054 localhost:5354 ESTABLISHED TCP WXP-DPBG8BS:1440 localhost:27015 ESTABLISHED TCP WXP-DPBG8BS:1447 localhost:1448 ESTABLISHED TCP WXP-DPBG8BS:1448 localhost:1447 ESTABLISHED TCP WXP-DPBG8BS:5354 localhost:1054 ESTABLISHED TCP WXP-DPBG8BS:27015 localhost:1440 ESTABLISHED
===================================== Need to have below output but output is not coming. Desired Output:- =====================================
port found:3743 port found:3744 port found:3745 port found:3746 ..............
===================================== Can you please help me to fix the code ?

Replies are listed 'Best First'.
Re: Extract Port value from netstat file
by jwkrahn (Abbot) on Apr 10, 2012 at 19:34 UTC

    You probably want something like this:

    use warnings; use strict; my $cmd = 'netstat'; my $pattern = qr/WXP-DPBG8BS\s*:\s*(\d+)/; open my $PIPE, '-|', $cmd or die "Could not open the pipe from '$cmd' +because:$!"; while ( <$PIPE> ) { if ( /$pattern/ ) { print "port found: $1\n"; } } close $PIPE or warn $! ? "Error closing $cmd pipe: $!" : "Exit status $? from $cmd";
Re: Extract Port value from netstat file
by Anonymous Monk on Apr 10, 2012 at 18:11 UTC
    Hi, here is your solution:
    while (defined(my $line = <FH>)) { if ($line =~ m/$pattern/) { printf "Port found: %d\n", (split $pattern, $line)[1]; } else { print "No Match\n"; } }
    P.S.: In the future, please use <code>...</code>.