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



Fredrik
Deleted

Feb 14, 2001, 4:13 PM


Views: 1117
=~ s ????

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


Views: 1112
Re: =~ s ????

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?