http://www.perlmonks.org?node_id=1010365


in reply to using function output ananymous array vs. named array in foreach

Neither snippet will do what you think it will do. chomp returns whatever is chomped off, not the line, so $a, will end up being a bunch of delimiters.

In terms of performance, there will be little to choose between them; they'll both be quite slow.

In terms of memory, the first will hang on to the memory used by @lines until you explicitly clean it.

You might find this does what you are after more efficiently:

my @lines = foo( 'bar' ); chomp @lines; my $a = join '', @lines; my $b; $b *= getVa( $_ ) for @lines; undef @lines;

As for scaling: if fun() can returns very large numbers of lines, building an array inside the function and then returning that array as a list will scale badly.

You could either pass a reference to the array into foo() and having it populate it; or return a reference to the array constructed internally; this avoiding the construction of the list and the copying of the array.

But better yet would be to move the chomping, concatenation and parsing inside the loop where the lines are read or generated, and return the concatenated string and the accumulated total; thus avoiding the construction of the array completely:

sub foo{ my $bar = shift; my( $a, $b ); ... while( my$line = getLine() ) { chomp $line; $a .= line; $b *= getVa( $line ) } return $a, $b; } my( $a, $b ) = foo( 'bar' );

With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.