Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations dencom on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Searching and printing

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi all :)

I have a question about searching in Perl

For example :

Lets say a have a text file like

212.12.12.2
199.2.3.1
210.3.3.2
212.12.12.2
199.65.78.123
112.34.55.6
212.12.12.2
199.88.77.12

What I want to do know is to find out how many lines that contains ip number 212.12.12.2.
It´s 3 okej, but how do I get Perl to understands it ?

 
Here:

[tt]
open(FILE,"ip.txt") || die("failed to open file:$!");
@data=<FILE>;
close(FILE);

$found = 0;
foreach $line (@data) {
if ($line eq &quot;212.12.12.2&quot;) {
$found++;
}
}
print &quot;$found\n&quot;;
[/tt]

You can replace the IP address with a variable so that you can search more than one IP.

Hope this helps,

-Vic vic cherubini
vikter@epicsoftware.com
====
Knows: Perl, HTML, JavScript, C/C++, PHP, Flash, Director
====
 
Hi,


I like to use the &quot;GREP&quot; function: you could write it as follows(I've put the values in a array for testing):

push @list,&quot;212.12.12.2&quot;;
push @list,&quot;199.2.3.1&quot;;
push @list,&quot;210.3.3.2&quot;;
push @list,&quot;212.12.12.2&quot;;
push @list,&quot;199.65.78.123&quot;;
push @list,&quot;112.34.55.6&quot;;
push @list,&quot;212.12.12.2&quot;;
push @list,&quot;199.88.77.12&quot;;

$arg = &quot;212.12.12.2&quot;;

$total = grep { /$arg/ } @list;

print &quot;Value for \$total is $total\n&quot;;


Thierry
 
Or, (TMTOWTDI);-).....
you could use regex's....

open(FILE,&quot;ip.txt&quot;) || die(&quot;failed to open file:$!&quot;);
while (<FILE>) { $buffer .= $_; }
close(FILE);

$ip = '212.12.12.2';
while ($buffer =~ /$ip/gs)
{
print &quot;Found $ip\n&quot;;
$count++;
}

Good Luck



keep the rudder amid ship and beware the odd typo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top