in reply to passing array as an argument

Parameters are flattened into a single list. If you want to pass an array and a scalar, you have to pass the scalar first: ($t, @ar) instead, or pass the array by reference.

You may learn how to use subroutines in Perl by having a look at perlsub. It's worth the 20 minute read if you plan to do much with Perl. You can even skip the more advanced sections on prototypes and overriding built-in functions. Most of what you're going to need comes before that point in the POD.


Dave


"If I had my life to live over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: passing array as an argument
by pg (Canon) on Oct 30, 2003 at 22:06 UTC

    Another thing is that, for performance reason, even there is only one parameter, it is still a good idea to pass array ref, instead of array.

    (davido didn't mention this simply because this was not asked in the original post)

    my @numb = (1..100); print sum(\@numb); sub sum { my $numb = shift; my $total; foreach (@$numb) {$total += $_}; return $total; }
      Another thing is that, for performance reason, even there is only one parameter, it is still a good idea to pass array ref, instead of array.

      Well, that's not strictly true. Perl passes by reference by default. Consider:

      perl -le 'sub scare { $_[0] = "boo!" } my $me; scare($me); print $me'
      Often people subvert this by copying the parameters themselves. Code like this is more common than not:
      sub foo { my @args = @_; # ... do stuff ... }
      And usually, it's fine because argument lists aren't very big.

      As for passing a single large array, though, there isn't much reason to pass a reference other than to be able to name it something nice in the sub rather than work directly with @_.

      -sauoq
      "My two cents aren't worth a dime.";