2016-09-21 285 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"; 
}