0

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?

4 Answers 4

2

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";
}

see perldoc for more on split and push.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! cool code! i think i found my problem - my while loop meant that there was only one element at the end of processing and i used push in the wrong way, which since fixing, has cured it!
0
my @array_one = (1, 3, 5, 7);
my @array_two = (2, 4, 6, 8);

my @new_array = (@array_one, @array_two);

1 Comment

i am not looking at combining arrays - i want to take the elements in array and instead of having "a b" as the element in row 1, i want "a" as the element in row 1, followed by "b" as the element in row 2 of array2
0

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.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.