Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • It’s easy to arrange:

    my $max_len = max map length, @strings;
    my $rx = qr/(@{[ join '|', map quotemeta, @strings ]})/;
    my $buf = '';
    while ( read $fh, $buf, 8096, length $buf ) {
        return $1 if $buf =~ $rx;
        substr $buf, 0, length $buf - $max_len, '';
    }

    As a bonus the code is shorter and clearer.

    The following is a tweak to avoid unnecessarily shrinking $buf when the space is needed for the read that immediately follows, and it may or may not be faster by a few percent. I didn’t benchmark (or even test) it.

    my $max_len = max map length, @strings;
    my $rx = qr/(@{[ join '|', map quotemeta, @strings ]})/;
    my $buf = '';
    my $offs = 0;
    while ( my $read = read $fh, $buf, 8096, $offs ) {
        substr( $buf, $offs + $read ) = ''; # throw away residue
        return $1 if $buf =~ $rx;
        substr( $buf, 0, $max_len ) = substr $buf, -$max_len;
        $offs = $max_len;
    }