charles hendry
charles hendry

Reputation: 1740

Rearranging arrays in Perl

Apologies for a simple question, but I'm very new to Perl! I have an array called @input which has the following data (note that the size of @input will not always be the same):

[0]  20004 11189 20207
[1]  12345 1234 123 12 1

I would like to create a new array called @elements which rearranges the data to be:

[0] 20004
[1] 11189
[2] 20207
[3] 12345
[4] 1234
[5] 123
[6] 12
[7] 1

Thanks!

Upvotes: 0

Views: 703

Answers (3)

jon
jon

Reputation: 6246

$tmparr = join(" ", @input);
@elements = split(" ", $tmparr);

Does this work?

Edit: TLP has provided a much better solution in the comment below, map split, @input

Upvotes: 0

TLP
TLP

Reputation: 67900

Well, either it's a one-dimensional array that needs splitting, or a two-dimensional that needs flattening. So, here's a sub for each task.

use v5.10;
use strict;
use warnings;

my @input1 = ("20004 11189 20207", "12345 1234 123 12 1");
my @input2 = ([qw"20004 11189 20207"], [qw"12345 1234 123 12 1"]);

sub one_dim { # Simple extract digits with regex
    return map /\d+/g, @_;
    # return map split, @_;  # same thing, but with split
}
sub two_dim { # Simple expand array ref
    return map @$_, @_;
}

my @new = one_dim(@input1);
say for @new;
@new = two_dim(@input2);
say for @new;

Upvotes: 2

dolmen
dolmen

Reputation: 8696

More efficient than Jon's answer:

@output = map { split / / } @input;

Upvotes: 1

Related Questions