0

I am parsing a text file and store words as keys inside a hash. Each key has an array as its value and stores how many times this word appears in the text as the first value and the probability of this word as the second value in the array.

Example:

my %ngram = (
    "word"=>("how many this word appear in text"," probability of this word")
);

How can I access or retrieve values of arrays inside a hash? I am posting code I used to accomplish that; I tried to print out these values, but it prints out as zeros as you see below:

0 *** 0 
0 *** 0

Any clue how I can retrieve or access these values?

while ( scalar @words > $inputs[0])
{
    $numerator="@words[0 .. $inputs[0]]";
    $denominator= "@words[0 .. ($inputs[0]-1)]";
    $nGram{$numerator}[0]=$nGram{$numerator}->[0]++;
    $nGram{$denominator}++;
    my $freq=$nGram{$numerator}->[0]/$nGram{$denominator};
    $nGram{$numerator}[1]=$freq;
    print "$nGram{$numerator}->[0] *** $nGram{$numerator}->[1]";
    shift @words;
}

1 Answer 1

2

Multi-level data structures in Perl, like a hash of arrays, don't store the array itself. It stores a reference to the array.

my %ngrams = (
    $word => [$num, $probability]
);

Note the [] instead of (). That makes an array reference. Now you can get at the value like anything else.

my $value = $ngrams{$word};

$value is an array reference. You have to dereference it to use it.

my $probability = $value->[1];

You can also do this in one shot.

my $probability = $ngrams{$word}[1];

You can read more about this in the Perl Reference Tutorial.


But a better data structure would be a hash of hashes.

my %ngrams = (
    $word => {
        appearances => $num,
        probability => $probability,
    }
);

Now instead of having to remember that element 0 is the number of appearances, and element 1 is the probability, you can reference them by name.

my $probability = $ngram{$word}{probability};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.