0

我有 7 个以下列方式定义的数组:

my @array1 = ();
..
my @array7 = ();

进而:

$array1[0] = "text goes here";
..
$array7[0] = "text goes here";

7 个数组,即 $array1[0] 到 $array1[24] 中的每个数组大约有 25 个元素。我需要经常在各种脚本中更改这些数组的内容。有时,因为数组的顺序很重要,我需要重新排列数组索引的顺序或删除某个位置的元素。这是一个真正的痛苦,因为我需要更改所有后续数组的索引。为了清楚起见,如果我删除 array1[12],那么我需要将 $array1[13] 更改为 $array1[12] 以及所有 7 个数组和所有后续索引位置(或移动 array1[ 的内容13] 到 array1[12] 等)

所以我的问题是,是否可以估算数组的索引,以便我可以切换数组位置而不必事后更正每个数组索引?像这样的东西:

$array1[$_] = "text 1 goes here";
..
$array7[$_] = "other text 1 goes here";

进而:

$array1[$_] = "text 2 goes here";
..
$array7[$_] = "other text 2 goes here";

其中 $_ 将被 1 替换为 7 个数组中每个数组的第一个索引,并由 2 替换为 7 个数组中每个数组的下一个元素...(最多 24 个元素)。

除了使用哈希和 Tie::Hash 之外,还有其他解决方案吗?

EDIT ok, let me clarify. I am looking for a script maintenance solution, no for a solution about the output of the script. I need to change the script myself (by hand) frequently and I do not want to change the numbers indexing all 24 positions of all 7 arrays by hand whenever I change something in these arrays. So my question was, is there a way to have the script impute the numbers indexing all positions of all arrays?

Using push as mvp was suggesting would be a proper solution. Are there any other solutions that could involve loops or something rather than using push 7X24 times?

4

2 回答 2

5

Not quite sure what your question is. You are probably complicating things quite a bit. Are you looking for splice?

my @a = (1 .. 4);
splice @a, 2, 1;    # remove 1 element, starting at index 2
# @a is now 1, 2, 4

splice can also insert elements and remove more than one element:

splice ARRAY or EXPR, OFFSET, LENGTH, LIST
于 2012-11-28T05:06:40.913 回答
0

You can use this approach:

my @array1;
push @array1, "text 1 goes here";
push @array1, "other text 1 goes here";
# ...
# or you can use loop as well:
for my $i (1..10) {
    push @array1, "text 1 instance $i goes here";
}

# do it for another one:
my @array2;
push @array2, "text 2 goes here";
push @array2, "other text 2 goes here";
# ...

You can even do this (little bit nasty because of dynamic variables):

for my $i (1..7) {
    for my $j (1..24) {
         push @{"array$i"}, "text $i, instance $j goes here";
    }
}
于 2012-11-28T22:21:28.153 回答