Home: Perl Programming Help: Beginner:
grep - search array, strange results. Help



ogit
Novice

Feb 15, 2017, 7:38 AM


Views: 2285
grep - search array, strange results. Help

Hi

I am struggling to understand how to get grep to search an array. We are using the array definition below.

Some searches work ok but others return blank. We are very confused. What are we doing incorrectly?

my $ip = "192.168.100.156";
my ( $index ) = grep { $ipslog1[$_] eq $ip } 0..$#ipslog1;
print "\%$index\%\n";
result -> %19%

my $ip = "192.168.100.99";
my ( $index ) = grep { $ipslog1[$_] eq $ip } 0..$#ipslog1;
print "\%$index\%\n";
result -> %14%

my $ip = "192.168.100.22"; # RETURNS BLANK??
my ( $index ) = grep { $ipslog1[$_] eq $ip } 0..$#ipslog1;
print "\%$index\%\n";
result -> %%

my $ip = "192.168.100.9"; # RETURNS BLANK??
my ( $index ) = grep { $ipslog1[$_] eq $ip } 0..$#ipslog1;
print "\%$index\%\n";
result -> %%

#array definition
my @ipslog1 = ();
$ipslog1[0] = "191.168.100.1";
$ipslog1[1] = "191.168.100.7";
$ipslog1[2] = "191.168.100.8";
$ipslog1[3] = "191.168.100.9";
$ipslog1[4] = "191.168.100.13";
$ipslog1[5] = "191.168.100.18";
$ipslog1[6] = "191.168.100.19";
$ipslog1[7] = "191.168.100.20";
$ipslog1[8] = "191.168.100.21";
$ipslog1[9] = "191.168.100.22";
$ipslog1[10] = "191.168.100.27";
$ipslog1[11] = "172.20.100.1";
$ipslog1[12] = "192.168.110.184";
$ipslog1[13] = "192.168.100.152";
$ipslog1[14] = "192.168.100.99";
$ipslog1[15] = "192.168.1.9";
$ipslog1[16] = "192.168.160.93";
$ipslog1[17] = "192.168.100.169";
$ipslog1[18] = "192.168.190.20";
$ipslog1[19] = "192.168.100.156";


FishMonger
Veteran / Moderator

Feb 15, 2017, 7:52 AM


Views: 2282
Re: [ogit] grep - search array, strange results. Help

Why are you surprised that those last two returned "BLANK"? Neither of those IP's are in your array.

It would be better to use a module designed for this purpose.
http://search.cpan.org/~rehsack/List-MoreUtils-0.416/lib/List/MoreUtils.pm#firstidx_BLOCK_LIST


ogit
Novice

Feb 15, 2017, 8:14 AM


Views: 2279
Re: [FishMonger] grep - search array, strange results. Help

Hi

Thank you for pointing that out. I had been going round in circles, I can't believe I did not see the 191's. Really appreciated. grep is working ok. Also, thank you for the code pointer - brilliant.

use List::MoreUtils ':all';
$index = firstidx { $_ eq $ip } @ipslog1;

Out of curiosity, which would be faster? grep or firstidx?


FishMonger
Veteran / Moderator

Feb 15, 2017, 8:24 AM


Views: 2276
Re: [ogit] grep - search array, strange results. Help

I would need to run a test, but off hand I'd say firstidx() would be faster.

You use the Benchmark module to find out.
http://search.cpan.org/~shay/perl-5.24.1/lib/Benchmark.pm