Perl:初学者.我应该使用哪种数据结构? [英] Perl: Beginner. Which data structure should I use?

查看:64
本文介绍了Perl:初学者.我应该使用哪种数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Okay, not sure where to ask this, but I'm a beginner programmer, using Perl. I need to create an array of an array, but I'm not sure if it would be better use array/hash references, or array of hashes or hash of arrays etc.

我需要一个匹配数组:@totalmatches

I need an array of matches: @totalmatches

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

Each match contains 6 elements(strings):

@matches = ($chapternumber, $sentencenumber, $sentence, $grammar_relation, $argument1, $argument2)

我需要将这些元素中的每一个推入 @matches 数组/hash/reference,然后将该数组/hash/reference 推入 @totalmatches 数组.

I need to push each of these elements into the @matches array/hash/reference, and then push that array/hash/reference into the @totalmatches array.

通过搜索文件并根据满足条件选择字符串来找到匹配项.

The matches are found based on searching a file and selecting the strings based on meeting the criteria.

问题

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

  1. Which data structure would you use?

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

Can you push an array into another array, as you would push an element into an array? Is this an efficient method?

你能同时推送所有 6 个元素,还是必须单独推送 6 个?

Can you push all 6 elements simultaneously, or have to do 6 separate pushes?

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

When working with 2-D, to loop through would you use:

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

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

感谢您的建议.

推荐答案

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

Do not push one array into another array. Lists just join with each other into a new list.

使用参考文献列表.

#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};
}

这篇关于Perl:初学者.我应该使用哪种数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆