#!/usr/bin/perl use strict; use warnings; use Fcntl qw /:seek/; use Benchmark qw /timethese cmpthese/; my $lines = shift || 50_000; my $file = "/tmp/big"; # First create a big data file. open my $fh => "> $file" or die "open: $!"; foreach (1 .. $lines) { foreach my $i (1 .. 3) { my $r = int rand 3; print $fh "abcdef" if $r == 0; print $fh "123456" if $r == 1; print $fh "<[{}]>" if $r == 2; } print $fh "\n"; } close $fh or die "close: $!"; my $words = "/tmp/words"; my $digits = "/tmp/digits"; my $punct = "/tmp/punct"; my @array = ([$words => '[a-z]'], [$digits => '[0-9]'], [$punct => '[^a-z0-9]']); sub many { foreach my $entry (@array) { open my $fh => ">", $entry -> [0] . ".m" or die "open: $!"; close $fh or die "close: $!"; } open my $fh => $file or die "open: $!"; while (<$fh>) { foreach my $entry (@array) { my ($f, $r) = @$entry; if (/$r/) { open my $fh1 => ">> $f.m" or die "open: $!"; print $fh1 $_; close $fh1 or die "close: $!"; } } } } sub one { open my $fh => $file or die "open: $!"; foreach my $entry (@array) { my ($f, $r) = @$entry; open my $fh1 => "> $f.o" or die "open: $!"; seek $fh => 0, SEEK_SET or die "seek: $!"; while (<$fh>) { print $fh1 $_ if /$r/ } close $fh1 or die "close: $!"; } } cmpthese -60 => { one => \&one, many => \&many, }; unlink $file or warn $!; unlink map {my $s = $_ -> [0]; ("$s.m", "$s.o")} @array; __END__ s/iter many one many 5.74 -- -95% one 0.267 2045% --