in reply to Counting occurances of a pattern in a file

Untested, and should be treated as psuedocode:
use strict; # Always use IO::File; # I like to localize filehandles. sub CountPatternInFile { my ( $filename, $pattern, $stop_pattern ) = @_; my $fh = IO::File->new( $filename ) or die $!; my $count = 0; while( <$fh> ) { $count += s/($pattern)/$1/g last if m/$stop_pattern/; } close $fh or die $!; return $count; }

Replies are listed 'Best First'.
RE (tilly) 2: Counting occurances of a pattern in a file
by tilly (Archbishop) on Aug 31, 2000 at 04:21 UTC
    Don't use IO::File.

    Why not?

    1. Twice as slow as native handles.
    2. You don't need it.
    3. I have tripped over bugs when using IO::* that I didn't with regular IO. Don't remember the combination of things that hit it, but procedural IO worked and the other did not.
    If you want lexical filehandles use the technique that I did at RE (tilly) 1: Merging files. Or with 5.6 don't worry about it because handles autovivify for you. (Just part of the ongoing improvements. :-)
RE: RE: Counting occurances of a pattern in a file
by Adam (Vicar) on Aug 31, 2000 at 03:19 UTC
    Or without a loop (also untested):
    use strict; # Always use IO::File; # I like to localize filehandles. sub CountPatternInFile { local $/; my ( $filename, $pattern, $stop_pattern ) = @_; my $fh = IO::File->new( $filename ) or die $!; $_ = <$fh>; close $fh or warn $!; ($_) = split /$stop_pattern/; return s/($pattern)/$1/g; }