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!
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);
See the section on "Pass by Reference" in perldoc perlsub.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With