Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to pass array to a subroutine?

Status
Not open for further replies.

makarandmk

Programmer
Jan 25, 2003
10
US
Hi I am novice user of perl.. my q is how to pass an array to a subroutine and how we can access different values of the array in the subroutine?
 
You need to do it with a reference, eg:
Code:
sub test {my ($arrayref) = @_; my @array = @$arrayref; return \@array;}

my @array = (a, bunch, of, stuff);
my $arrayref = test(\@array);

A better way would be to pass objects, which are already references.
Sincerely,

Tom Anderson
CEO, Order amid Chaos, Inc.
 
Thanks very much.. it worked for me..

regards,
Makarand
 
There is a fairly complete discussion of this topic in the Man pages under perlref. You should take a looke there for a more complete discusion.

You may find that passing a hash reference is a little more useful

$hashreference={'this'=>"$that",
'mine'=>"$notyours"}

test($hashreference);

sub test {
my $hashreference = shift;
#dereference a hash key
print $hashrefernce->{this};
}

 
You can also just pass the array. You can do this if you want an array to be the last, or only, parameter of a function.

[tt]sub arrayTest {
my @parms = @_;
print join(", ", @parms);
}

my @a = ("this", "is", "a", "test");
arrayTest(@a);
[/tt]

(Obscurely, you can also pass an array to a function that takes several parameters. The first element of the array is the first parameter, second the second, etc. Any remaining elements would be left for the final [array] parameter.)

If you plan to change the array or its values, you'll need to go with the array ref, though.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top