Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array and scalar to a Perl subroutine [duplicate]

Possible Duplicate: How do pass one array and one string as arguments to a function?

I have a function, or subroutine, that takes in the first parameter as an array and the second parameter as a scalar. For example,

sub calc {     my @array = $_[0];     my $scalar = $_[1];     print @array, $scalar; } 

The problem is that the function is making the array equal to the first value of the array passed in, and the scalar to be the second value of the array passed in. When I want the first array to be the entire array, I do not need to make a deep copy of the array. For example,

my @array = ('51', 'M'); my $scalar = 21; 

and

calc(@array, $scalar) 

will print 51 M when I want 51 M 21.

like image 367
E.Cross Avatar asked May 23 '12 22:05

E.Cross


People also ask

How do I pass multiple arrays to a SubRoutine in Perl?

You have to pass them like this: two_array_sub( @$arr_ref, @$brr_ref ); However, because making "array expressions" gets really ugly quickly with arrays nested deep, I often avoid Perl's fussiness as you can overload the type of reference Perl will take by putting it in a "character class" construct.

How do I pass a variable to a SubRoutine in Perl?

Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.

What does @_ mean in Perl?

Using the Parameter Array (@_) Perl lets you pass any number of parameters to a function. The function decides which parameters to use and in what order.


1 Answers

You need to pass it in as a reference:

calc(\@array, $scalar)

And then access it as: my @array = @{$_[0]};

like image 195
happydave Avatar answered Sep 23 '22 16:09

happydave