Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Beginner. Which data structure should I use?

Tags:

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.

I need an array of matches: @totalmatches

Each match contains 6 elements(strings):

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

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.

QUESTIONS

  1. Which data structure would you use?

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

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

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

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

Thanks for any advice.

like image 557
Jon Avatar asked Jun 09 '11 20:06

Jon


1 Answers

Which data structure would you use?

An array for a ordered set of things. A hash for a set of named things.

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

If you try to push an array (1) into an array (2), you'll end up pushing all the elements of 1 into 2. That is why you would push an array ref in instead.

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

Look at perldoc -f push

push ARRAY,LIST

You can push a list of things in.

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

Nested foreach is fine, but that syntax wouldn't work. You have to access the values you are dealing with.

for my $arrayref (@outer) {
    for my $item (@$arrayref) {
        $item ...
    }
}
like image 73
Quentin Avatar answered Sep 23 '22 14:09

Quentin