2016-09-21 120 views
-4

請,我想知道如何使用Perl將數組的元素添加到另一個數組。 如果有一個循環可以用來爲X數組創建一個計數器。使用Perl將數組的元素添加到另一個數組

#!/usr/local/bin/perl 
$line = <STDIN>; 
@array = split(/ /,$line); 
print"$array[4]\n"; 
@X[0][email protected][4]; 
@X[1][email protected][4]; 
@X[2][email protected][4]; 
@X[3][email protected][4]; 
print @X; 
+3

你將不得不對擴大你想要什麼去完成。另外 - 打開'使用嚴格;使用警告;'因爲這會告訴你在你的代碼中的一些錯誤。 – Sobrique

+0

好的,謝謝。此外,我已經打開使用嚴格;並使用警告;他們向我展示了我的代碼中的很多錯誤,這些錯誤非常方便。 –

+3

然後在使用嚴格和警告之後,在此處添加無錯代碼,顯示您正在嘗試完成的任務,因爲@Sobrique已經寫過。 – AbhiNickz

回答

2

我想如何數組的元素添加到使用Perl另一個。

如果你有

my @data  = ('a', 'b', 'c'); 
my @addition = ('x', 'y', 'z'); 

那麼你可以使用push@addition內容添加到@data這樣

push @data, @addition; 

現在@data將包含('a', 'b', 'c', 'x', 'y', 'z')

其餘你的問題不清楚

-1

我相信你想讀取每個輸入的第五個單詞,然後存儲在數組中。你可以參考我的示例代碼:

use strict; 
use warnings; 

my @x; 
while(<STDIN>){ 
    my $line = $_; 
    chomp $line; 
    my @array = split(/\s/, $line); 
    push (@x, $array[4]); 
    print "Your array: @x\n"; 
} 
運行這段代碼的時候,如果你輸入「 a b c d e」它將存儲 e數組 @x,然後如果你繼續鍵入新行「 1 2 3 4 5」值 5將存入

@x等。 例如:

a b c d e 
Your array: e 
1 2 3 4 5 
Your array: e 5 
one two three four five 
Your array: e 5 five 

此外,我建議你檢查至少5個字的每一行輸入如下的條件:

if (scalar(@array) < 5){ 
    print "Require at least 5 words\n"; 
} else { 
    push (@x, $array[4]); 
    print "Your array: @x\n"; 
} 
相關問題