Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: passing arrays to subroutines

by prasadbabu (Prior)
on Mar 16, 2005 at 13:06 UTC ( #439928=note: print w/ replies, xml ) Need Help??


in reply to passing arrays to subroutines

@a= (1, 2, 3); &test(@a); sub test {my (@b)= @_; pirnt "@b"; }

If you want to pass more than one array you can make use of reference. see perlref

Prasad


Comment on Re: passing arrays to subroutines
Download Code
Re^2: passing arrays to subroutines
by Anonymous Monk on Mar 16, 2005 at 13:16 UTC
    That doesn't pass an array into the sub. It passes a list into the sub. In fact, you cannot pass an array into a sub in Perl - the best you can do is passing a reference, either explicitely using \ (caller in charge), or implicitely using a prototype (callee in charge).

      Just to expand on this point for the OP's benefit, consider:

      use strict; use Dumpvalue; my $dumper = Dumpvalue->new(); my @a = (3, 1, 4, 1); my @b = (5, 9); my @c = (2, 6, 5); sub ex1 { map 10*$_, @_; } $dumper->dumpValue([ex1(@a)]); print "\n"; # array refs sub ex2 { map scalar @$_, @_; } $dumper->dumpValue([ex2(\@a, \@b, \@c)]); print "\n"; # implicit array refs through prototypes sub ex3 (\@\@\@) { map scalar @$_, @_; } $dumper->dumpValue([ex3(@a, @b, @c)]); print "\n"; __END__ 0 30 1 10 2 40 3 10 0 4 1 2 2 3 0 4 1 2 2 3
      Note that the bodies of ex2 and ex3 are identical. IMO, however, ex2 is superior, because it can take as arguments any number of array refs, whereas ex3 must take exactly three arrays as arguments.

      Follow-up question: is there any way to define a sub that takes as input one or more arrays?

      the lowliest monk

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://439928]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (9)
As of 2014-12-26 13:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (171 votes), past polls