> Hello,
> 
> I just started using perl and want to rewrite a simple bash 
> script i've been
> using in the past to perl.
> 
> I want to cat file|grep "foo bar"|wc -l and tried it the 
> following way which
> worked for foobar as one word and not as two words.
> 
> ---
> #!/usr/bin/perl
> $logfile = "/var/log/logfile";
> $grep_cmd = "/bin/grep";
> $string = $ARGV[0];
> $count = 0;
> 
> open(LOG, "cat $logfile|$grep_cmd $string|") || die "Ooops";
> while($line = <LOG>) {
>             $count++;
> }
> 
> print "$count\n";

Paging Randal for UUOC award!

No need to use external commands at all!!!

The first argument is the perl regex to search for, the second argument
is the file in which to count matching lines.

#!/usr/bin/perl
use strict;
use warnings;

my $str = $ARGV[0];

my $search_regex;

eval { $search_regex = qr/$str/ };
if ($@) {
        die "Invalid regex passed as first argument: [EMAIL PROTECTED]";
}

my $f = $ARGV[1];

my $c = 0;
open F, $f or die "Can't open $f for reading: $!";
while (<F>) {
        ++$c if /$search_regex/o; # I don't remember if the "o" helps
here or not as $search_regex is unchanging....
}
close F;
print $c, "\n";

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to