2 arrays perl multidimensional-array
我希望能够将数组放入数组中.例如,我可能有这样的数组:
my @array1 = ("element 1","element 2","element 3");
Run Code Online (Sandbox Code Playgroud)
然后我有另一个阵列
my $array_ref = ["this will", "go between", "element 1 and 2"];
Run Code Online (Sandbox Code Playgroud)
我想$array_ref放入第一个,以便第一个数组看起来像这样:
("element 1",["this will", "go between", "element 1 and 2"],"element 2","element 3")
Run Code Online (Sandbox Code Playgroud)
我似乎无法做到这一点.我看着谷歌,一无所获.
所以你使用splice用你想要的元素替换以元素1开头的0个元素(第二个元素,第一个元素是元素0):
splice( @array, 1, 0, ["this will", "go between", "element 1 and 2"] );
Run Code Online (Sandbox Code Playgroud)
或者你的意思是:
splice( @array, 1, 0, "this will", "go between", "element 1 and 2" );
Run Code Online (Sandbox Code Playgroud)
如果你不想要嵌套数组.
需要记住的重要一点是 () 和 [] 之间的区别。'()' 为您提供元素列表,例如。(1, 2, 3) 然后您可以将其分配给数组变量,如下所示 -
my @listOfElem = (1, 2, 3);
Run Code Online (Sandbox Code Playgroud)
'[]' 是一个数组引用,返回一个标量值,您可以将其合并到列表中。
my $refToElem = ['a', 'b', 'c'];
Run Code Online (Sandbox Code Playgroud)
在您的情况下,如果您正在初始化第一个数组,那么您可以简单地插入第二个数组元素,如下所示,
my @listOfElem = (1, 2, ['a', 'b', 'c'], 3);
#This gives you a list of "4" elements with the third
#one being an array reference
my @listOfElem = (1, 2, $refToELem, 3);
#Same as above, here we insert a reference scalar variable
my @secondListOfElem = ('a', 'b', 'c');
my @listOfElem = (1, 2, \@secondListOfElem, 3);
#Same as above, instead of using a scalar, we insert a reference
#to an existing array which, presumably, is what you want to do.
#To access the array within the array you would write -
$listOfElem[2]->[0] #Returns 'a'
@{listOfElem[2]}[0] #Same as above.
Run Code Online (Sandbox Code Playgroud)
如果您必须在数组中间动态添加数组元素,那么只需使用“拼接”,如其他帖子中详细介绍的那样。
| 归档时间: |
|
| 查看次数: |
6044 次 |
| 最近记录: |