in reply to Re: TIMTOWTDI - printing an array
in thread TIMTOWTDI - printing an array

or
sub { print @_ }->($_) for @arr;

Replies are listed 'Best First'.
Re^3: TIMTOWTDI - printing an array
by johngg (Canon) on Jun 21, 2012 at 08:29 UTC

    That also works but you are incurring the expense of creating and invoking the subroutine for each and every element of the array rather than just once. This might have an impact on performance.

    Cheers,

    JohnGG

Re^3: TIMTOWTDI - printing an array
by johngg (Canon) on Jun 21, 2012 at 10:54 UTC

    I think this benchmark code confirms my point regarding the expense of continually creating and invoking anonymous subroutines.

    use strict; use warnings; use Benchmark qw{ cmpthese }; my @arr = ( 1 .. 1e6 ); my $rcOneElement = sub { my $aref = shift; sub { my $var = shift }->( $_ ) for @$aref; }; my $rcAllElements = sub { my $aref = shift; sub { my $var = shift while @_ }->( @$aref ); }; cmpthese ( -5, { OneElement => sub { $rcOneElement->( \ @arr ) }, AllElements => sub { $rcAllElements->( \ @arr ) }, } );

    The output.

    Rate OneElement AllElements OneElement 2.59/s -- -58% AllElements 6.16/s 138% --

    However, I am good at cocking up benchmarks so I could be deluding myself :-/

    Cheers,

    JohnGG