开发者

Passing arrays to a subroutine that prints each array separately

开发者 https://www.devze.com 2023-03-16 08:40 出处:网络
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.

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.


use strict;
use warnings;
use English qw<$LIST_SEPARATOR>;

my @A1 = (1, 2, 3);
my @A2 = (4, 5, 6);
{   local $LIST_SEPARATOR = '';
    my @a = map { "@$_" } \@A1, \@A2;
    $LIST_SEPARATOR = '@@@';
    print "@a\n";
}

You also could have used join (po-tay-to, po-tah-to).

my @a = map { join( '', @$_ ) } \@A1, \@A2;
print join( '@@@', @a ), "\n";
0

精彩评论

暂无评论...
验证码 换一张
取 消