Perl:初学者.我应该使用哪种数据结构?

Jon*_*Jon 5 perl

好吧,不知道在哪里问这个,但我是初学程序员,使用Perl.我需要创建一个数组的数组,但我不确定是否更好地使用数组/哈希引用,哈希数组或哈希数组等.

我需要一系列匹配: @totalmatches

每个匹配包含6个元素(字符串):

@matches = ($chapternumber, $sentencenumber, $sentence, $grammar_relation, $argument1, $argument2)
Run Code Online (Sandbox Code Playgroud)

我需要将每个元素推入@matches数组/ hash/reference,然后将该数组/散列/引用推送到@totalmatches数组中.

基于搜索文件并基于满足标准选择字符串来找到匹配.

质询

  1. 你会使用哪种数据结构?

  2. 你可以将数组推入另一个数组,就像将元素推入数组一样吗?这是一种有效的方法吗?

  3. 你可以同时推动所有6个元素,还是必须进行6次单独推送?

  4. 使用2-D时,要循环使用:

    foreach(@totalmatches){foreach(@matches){...}}

谢谢你的建议.

Que*_*tin 6

你会使用哪种数据结构?

一组有序的事物的数组.一组命名事物的哈希.

你可以将数组推入另一个数组,就像将元素推入数组一样吗?这是一种有效的方法吗?

如果你试图将一个数组(1)推入一个数组(2),你最终会将1的所有元素推入2.这就是为什么你要推送一个数组ref.

你可以同时推动所有6个元素,还是必须进行6次单独推送?

看着 perldoc -f push

push ARRAY,LIST
Run Code Online (Sandbox Code Playgroud)

你可以推送一系列的东西.

使用2-D时,要循环使用:

嵌套的foreach很好,但是这种语法不起作用.您必须访问正在处理的值.

for my $arrayref (@outer) {
    for my $item (@$arrayref) {
        $item ...
    }
}
Run Code Online (Sandbox Code Playgroud)


Zha*_*Chn 3

不要将一个数组推入另一数组。列表只是相互连接成一个新列表。

使用参考文献列表。

#create an anonymous hash ref for each match
$one_match_ref = {
     chapternumber => $chapternumber_value, 
     sentencenumber => $sentencenumber_value, 
     sentence => $sentence_value,
     grammar_relation => $grammar_relation_value, 
     arg1 => $argument1, 
     arg2 => $argument2
};

# add the reference of match into array.
push @all_matches, $one_match_ref;

# list of keys of interest
@keys = qw(chapternumber sentencenumber sentence grammer_relation arg1 arg2);
# walk through all the matches.
foreach $ref (@all_matches) {
    foreach $key (@keys) {
        $val = $$ref{$key};

    }
    # or pick up some specific keys
    my $arg1 = $$ref{arg1};
}
Run Code Online (Sandbox Code Playgroud)