Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arrays to a subroutine that prints each array separately

I know that this is probably a simple fix, but I have not been able to find the answer through google and searching through the questions here.

My goal is to pass multiple arrays to a subroutine that simply iterates through each array separately and prints each array with something before and after it.

What I have:

@A1 = (1, 2, 3);
@A2 = (4, 5, 6);

printdata(@A1, @A2) ;

sub printdata {
   foreach(@_) {
      print "$_" ; 
      print "@@@"
      }
   }

What I am attempting to get is:

123@@@456@@@

Instead its treating both arrays as one and iterating through each variable in the array, Putting the separator after every variable vice the entire array.

1@@@2@@@3@@@etc.....

I am not sure how to get the subroutine to treat the arrays as separate rather than as one.

Any Help would be greatly appreciated!

like image 323
Kevin Avatar asked Dec 12 '22 11:12

Kevin


2 Answers

You need to pass the arrays as references:

@A1 = (1, 2, 3);
@A2 = (4, 5, 6);

printdata(\@A1, \@A2) ;

sub printdata {
   foreach(@_) {
      print @$_ ; 
      print "@@@"
      }
}

The sub call expands the arrays into a list of scalars, which is then passed to the sub within the @_ variable. E.g.:

printdata(@A1, @A2);

is equal to:

printdata(1,2,3,4,5,6);
like image 97
TLP Avatar answered Jan 05 '23 00:01

TLP


See the section on "Pass by Reference" in perldoc perlsub.

like image 31
Dave Cross Avatar answered Jan 04 '23 23:01

Dave Cross