Perl: the Markov chain saw PerlMonks

### Re: filtering and dividing an array

by Dhanasekar (Acolyte)
 on Nov 29, 2008 at 10:31 UTC ( #726760=note: print w/replies, xml ) Need Help??

in reply to filtering and dividing an array

For joining the two arrays into a single array below is the example. The operation will be done for the number of elements in the array1, i.e., if there are 4 elements in the list then first 4 elements will be processed irrespective of the number of elements in array2.
```#/usr/bin/perl

use Data::Dumper;

## Populating the Arrays with some values.
@array1 = ( 1,2,3,4 ) ;
@array2 = ( 'one', 'two', 'three', 'four' );

## Initialise the index for the array
\$i = 0;

## Join the two array 'array1', 'array2' in a single array named 'arra
+y'
map {  \$array[\$i][0] = \$array1[\$i] ; \$array[\$i][1] = \$array2[\$i]; \$i++
+  } @array1 ;

print Dumper @array;
I am not sure whether you have asked this !!

Replies are listed 'Best First'.
Re^2: filtering and dividing an array
by oko1 (Deacon) on Nov 29, 2008 at 14:03 UTC

That's not exactly what I would call "joining two arrays"; you've actually created a List of Lists. Joining arrays is much simpler than that:

```my @a = 1 .. 4; my @b = "a" .. "d";
my @c = (@a, @b);

# You could even do this - no need to create a new variable:
@a = (@a, @b);

# Or...
push @a, @b;

There's also no need for the complex and hard-to-read map statement if you wanted to create a LoL; just as in your example, this assumes that the first array is the same length or shorter than the second one:

```my @c;
push @c, [ \$a[\$_], \$b[\$_] ] for 0 .. \$#a;

Update: Added the "Or..." "push" method.

--
"Language shapes the way we think, and determines what we can think about."
-- B. L. Whorf

Create A New User
Node Status?
node history
Node Type: note [id://726760]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (14)
As of 2018-04-25 14:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (90 votes). Check out past polls.

Notices?