#!/usr/bin/perl # # Is map really faster then foreach? # use Benchmark qw( cmpthese timethese); use warnings; use strict; my @array = `cat /usr/share/dict/linux.words`; sub for_loop { for (@array){ if ($_ =~ /^tsaavik$/) { print $_; } } } sub foreach_loop { foreach my $line (@array){ if ($line =~ /^tsaavik$/) { print $line; } } } sub map_loop { map { print $_ if ($_ =~ /^tsaavik$/) } @array; } timethese (-30, { # number indicates seconds to run the test for (-5 is 5seconds) or total test runs to do (if number +) 'foreach method' => sub { foreach_loop() }, 'for method' => sub { for_loop() }, 'map method' => sub { map_loop() }, });