CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
=~ s ????

 



Fredrik
Deleted

Feb 14, 2001, 4:13 PM

Post #1 of 2 (473 views)
=~ s ???? Can't Post

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 now 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 ?







rGeoffrey
User / Moderator

Feb 14, 2001, 6:38 PM

Post #2 of 2 (468 views)
Re: =~ s ???? [In reply to] Can't Post

Consider this block of code...


Code
#!/usr/local/bin/perl 

use strict;

my $source = <<EOF;
212.12.12.2
199.2.3.1
210.3.3.2
212.12.12.2 212.12.12.2
199.65.78.123
112.34.55.6
212.12.12.2
199.88.77.12
EOF

my @rows = split ("\n", $source);
my $ip = '212.12.12.2';

my $count;

Now here are three options that might do what you want to @rows...


Code
foreach (@rows) { 
$count++ if (/$ip/);
}

print "'$ip' found on $count of ", scalar (@rows), " lines\n";

$count = ($source =~ s/$ip/$ip/g);

print "'$ip' found on $count of ", scalar (@rows), " lines\n";

$count = grep { /$ip/ } @rows;

print "'$ip' found on $count of ", scalar (@rows), " lines\n";

I made a small change to the data so one of these three solutions will give the wrong answer. But learning which one is left as an exercise for the reader.



---
Sun Sep 9, 2001 - 1:46:40 GMT, a very special second in the epoch. How will you celebrate?

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives