Perl Concatenate 2 arrays. Combining array1 element 1 and array 2 element 1 into a single string.

TristinColby
TristinColby used Ask the Experts™
on
I'm trying to concatenate 2 arrays. The catch is that I'm trying to concatenate the elements. like the following

my @array = qw/one two three four/;
my @array2 = qw/a b c d/;

I want the result to be stored in a new array.
the result should be like:
one:a, two:b, three:c, four:d
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2014
Top Expert 2015
Commented:
@newarray = map{"$array[$_]:$array2[$_]"} $[..$#array ;

Author

Commented:
Here's the original code: This works.
      Original Code:
      my $ref_svc = $dbh->selectcol_arrayref("SELECT Name from Services");
      my $ref_id = $dbh->selectcol_arrayref("SELECT ID from Services");
      my %hash = ();
     @hash{@{$ref_svc}} = @{$ref_id};

I realized i need to append a port on the end of the service name as i mentioned before so I tried this but it doesn't work and I'm stumped.

      my $ref_svc = $dbh->selectcol_arrayref("SELECT Name from Services");
      my $ref_id = $dbh->selectcol_arrayref("SELECT ID from Services");
      my $ref_port = $dbh->selectcol_arrayref("SELECT Port from Services");
      my %hash = ();
      my @tmp = ();
      @tmp = map{"@{$ref_svc}[$_]:@{$ref_port}[$_]"} $[..@#{$ref_svc};
      @hash{@tmp} = @{$ref_id};  

Author

Commented:
Okay I figured it out. The problem is the way i'm getting the length of the array.  So how do i get the length of the array reference?

Author

Commented:
figured it out.  @{$array}-1 works.

Thanks ozo.
ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
or $#$array

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial