vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

Here which one is the efficient way of passing array to a function print_array

our @foo = ("ree1", "ree2", "ree3"); print_array(*foo); my @foo = ("ree3","ree2","ree1"); print_array(\@foo); sub print_array { local (*printarr) = @_; foreach my $val (@printarr) { print "$val\n"; } }
Vinoth,G

Replies are listed 'Best First'.
Re: Best way to pass a array to a function
by moritz (Cardinal) on Apr 27, 2009 at 12:20 UTC
    Why don't you try it? Benchmark is your friend.
Re: Best way to pass a array to a function
by Marshall (Canon) on Apr 27, 2009 at 17:48 UTC
    I would say in general, for reasons that are independent of performance, a lexical "my" variable is preferred over a package level "our" variable. Also besides scoping issues, a "my" variable is faster than a "local" variable. A shift is very slightly faster than a "my $var = @_;"( missed parens! oops..(my $var)= @_;) when the sub has one arg passed to it. But in this case, I don't see how it could make much difference.

    If you are going to do some benchmarking, then I would suggest this code:

    print_array2 (\@foo); sub print_array2 { my $array_ref = shift; print join ("\n", @$array_ref), "\n"; }
    I am curious as what you are doing as I've never seen a Perl program that was limited by speed of output (much more problematic is processing of the input data!). Print like all I/O is an expensive operation and time to do it usually dwarfs any calculation required to get the thing to print formatted. I would at least suggest adding the above code into your benchmarking - it will run very quickly.Of course, you can also try:
    sub print_array2 { my $array_ref = shift; foreach (@$array_ref)) { print "$_\n"; } }
Re: Best way to pass a array to a function
by pemungkah (Priest) on Apr 27, 2009 at 21:07 UTC
    I'd like to note that *foo passes all of the following:
    • $foo
    • @foo
    • %foo
    • &foo
    • the filehandle foo
    \@foo passes only @foo. In terms of maintainability, go with the reference even if it's a teeny bit slower because someone maintaining code more complex than print_array might be confused as to which thing you really meant to pass in and use; worse, there's the possibility of accidentally using one of those variables in the subroutine and absentmindedly leaving off the my ... for which you will get no error message!

    Pass globs only when there's no other way to deal with the problem - and as of Perl 5.8 (at least), there's always a better way: references, or a filehandle in a lexical variable.