#!/usr/bin/perl -w use strict; use Benchmark qw(timethese); my $repeat = 10; my $text = ('abc' x $repeat) . 'gotcha' . ('xyz' x $repeat); my ($pre,$match,$post); print "OS: $^O - Perl: $]\n"; timethese( 100000, { 'unpack' => sub { if ($text =~ /gotcha/) { $pre = prematch($text); $post = postmatch($text); $match = match($text); } }, 'substr' => sub { if ($text =~ /gotcha/) { $pre = substr_prematch($text); $post = substr_postmatch($text); $match = substr_match($text); } }, } ); if ($text =~ /gotcha/) { print "unpack\n"; print "prematch :", prematch($text), "\n"; print "match :", match($text), "\n"; print "postmatch :", postmatch($text), "\n"; print "substring\n"; print "prematch :", substr_prematch($text), "\n"; print "match :", substr_match($text), "\n"; print "postmatch :", substr_postmatch($text), "\n"; } sub prematch { return unpack "a$-[0]", $_[0]; } sub postmatch { return unpack "x$+[0] a*", $_[0]; } sub match { my $len = $+[0] - $-[0]; unpack "x$-[0] a$len", $_[0]; } sub substr_match { substr( $_[0], $-[0], $+[0] - $-[0] ) } sub substr_prematch { substr( $_[0], 0, $-[0] ) } sub substr_postmatch { substr( $_[0], $+[0] ) } __END__ (output edited to fit the page better) OS: cygwin - Perl: 5.008 Benchmark: timing 100000 iterations of substr, unpack... substr: 2 wallclock secs ( 1.92 usr + 0.00 sys = 1.92 CPU) unpack: 11 wallclock secs (11.89 usr + 0.00 sys = 11.89 CPU) unpack prematch :abcabcabcabcabcabcabcabcabcabc match :gotcha postmatch :xyzxyzxyzxyzxyzxyzxyzxyzxyzxyz substring prematch :abcabcabcabcabcabcabcabcabcabc match :gotcha postmatch :xyzxyzxyzxyzxyzxyzxyzxyzxyzxyz OS: MSWin32 - Perl: 5.006001 Benchmark: timing 100000 iterations of substr, unpack... substr: 3 wallclock secs ( 1.93 usr + 0.00 sys = 1.93 CPU) unpack: 4 wallclock secs ( 3.87 usr + 0.00 sys = 3.87 CPU) unpack OS: linux - Perl: 5.006001 Benchmark: timing 100000 iterations of substr, unpack... substr: 2 wallclock secs ( 2.26 usr + 0.00 sys = 2.26 CPU) unpack: 4 wallclock secs ( 3.90 usr + 0.00 sys = 3.90 CPU) unpack #### sub prematch { unpack sprintf("a%d",$-[0]), $_[0]; } sub postmatch { unpack sprintf( "x%d a*", $+[0]) , $_[0]; } sub match { unpack sprintf ("x%d a%d", $-[0], $+[0] - $-[0] ), $_[0]; }