If I have an @array with rows:
row 1: a b
row 2: b c
row 3: c d
How do I obtain a new @array2 with all the elements in one column, so @array2 = a b b c c d?
your question is somewhat ambiguously worded, which is likely because you are new to perl. you haven't provided your input or expected output in perl syntax, but based on your response to a prior answer, i'll take a guess:
## three rows of data, with items separated by spaces
my @input = ( 'a b', 'b c', 'c d' );
## six rows, one column of expected output
my @expected_output = ( 'a', 'b', 'b', 'c', 'c', 'd' );
taking this for your expected input and output, one way to code a transformation is:
## create an array to store the output of the transformation
my @output;
## loop over each row of input, separating each item by a single space character
foreach my $line ( @input ) {
my @items = split m/ /, $line;
push @output, @items;
}
## print the contents of the output array
## with surrounding bracket characters
foreach my $item ( @output ) {
print "<$item>\n";
}
my @array_one = (1, 3, 5, 7);
my @array_two = (2, 4, 6, 8);
my @new_array = (@array_one, @array_two);
Here's another option:
use Modern::Perl;
my @array = ( 'a b', 'b c', 'c d' );
my @array2 = map /\S+/g, @array;
say for @array2;
Output:
a
b
b
c
c
d
map operates on your list in @array, applying a regex (matching non-whitespace characters) to each element in it to generate a new list that's placed into @array2.
One other possible interpretation of your initial data is that you have an array of array references. This "looks" like a 2D array and thus you would talk about "rows". If that's the case then try this
#!/usr/bin/env perl
use warnings;
use strict;
my @array1 = (
['a', 'b'],
['b', 'c'],
['c', 'd'],
);
# "flatten" the nested data structure by one level
my @array2 = map { @$_ } @array1;
# see that the result is correct
use Data::Dumper;
print Dumper \@array2;