in reply to TIMTOWTDI - printing an array

Anonymous subroutine perhaps?

knoppix@Microknoppix:~$ perl -E ' > @arr = qw{ 11 22 33 44 }; > sub { say shift while @_ }->( @arr );' 11 22 33 44 knoppix@Microknoppix:~$

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: TIMTOWTDI - printing an array
by choroba (Cardinal) on Jun 20, 2012 at 23:43 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

      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