user3586606 user3586606 - 2 months ago 16
Perl Question

Grep elements from array that exists in output

Is there any way to use grep to find only elements that exists in specific array?
For example :

my @IPS ={"10.20.30","12.13.14","30.40.50"};

my $cmd = `netstat -Aa | grep -c IPS[0] OR IPS[1] OR IPS[2] `

print "$cmd";


I want cmd to return the number of IPS (only those found in the array) that exists in the output of netstat command.
I know I can use " | " or condition but assume that I do not know the number of elements in array.

Answer

Your @IPS array does not contain what you think it contains. I think you probably wanted:

my @IPS = ("10.20.30","12.13.14","30.40.50");

And I'd write that as:

my @IPS = qw(10.20.30 12.13.14 30.40.50);

I know I can use " | " or condition but assume that I do not know the number of elements in array

I don't think that matters at all.

# Need quotemeta() to escape the dots
my $IP_str = join '|', map { quotemeta $_ } @IPS;
my $IP_re  = qr/$IP_str/;

# Keep as much of the processing as possible in Perl-space
my @found = grep { /$IP_str/ } `netstat -Aa`;
say scalar @found;

An alternative to the regex, is to turn @IPS into a hash.

my %IP = map { $_ => 1 } @IPS;
my @found = grep { $IP{$_} } `netstat -Aa`;
say scalar @found;

Update: Actually, that last example doesn't work. You would need to extract the IP addresses from the netstat output before matching against the hash. but I've left it there in case it inspires anyone to expand it.

Comments