2012-02-02 55 views
0

對於一個簡單的問題抱歉,但我對Perl很陌生! 我有一個名爲陣列@input它有如下數據(注意@input的大小並不總是相同):在Perl中重新排列數組

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

我想創建一個新的陣列稱爲@elements其重新排列數據爲:

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

謝謝!

+7

當你說'[0] 20004 11189 20207',你的意思是元素[0]包含一個字符串使用這些值,或該元素[0]是本身含有三個值另一個數組?如果您可以發佈調試器命令'x @ input'的輸出將會非常有幫助。 – 2012-02-02 17:23:39

回答

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

這是行得通嗎?

編輯:TLP提供在下面的評論一更好的解決方案,map split, @input

+0

謝謝!這項工作 – 2012-02-02 17:33:10

+1

爲什麼在不需要時使用轉換變量?當插值做同樣的事情時加入? '@elements = split'',「@input」' – TLP 2012-02-02 17:48:24

+0

爲什麼在不需要時使用'split'參數? '@input = map {split} @ input'。 – 2012-02-02 18:12:55

1

比喬恩的回答更高效:

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

'@output = map split,@input' – TLP 2012-02-02 17:50:42

+0

@TLP請將您的解答作爲答案 – Borodin 2012-02-02 18:44:00

+0

@Borodin我發佈了一個答案。使用'split'是dolmen的答案,我使用'/ \ d +/g',它基本上做同樣的事情。 – TLP 2012-02-02 18:51:08

2

好,無論是它的一維數組需要分裂,或者需要扁平化的二維。所以,這是每個任務的一個子集。

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;