3

I'm trying to dynamically create an associative array whose values are arrays. My current attempt is as follows but I'm not sure if it is correct or efficent.

foreach $line (@lines)                               # read line from a text dictionary 
{
    chomp( $line );
    my($word, $definition) = split(/\s/, $line, 2); # 
    $definition =~ s/^\s+|\s+$//g ;                 # trim leading and trailing whitespace

    if( exists $dict{$word} )
    {
        @array = $dict{$word};
        $len = scalar @array;
        $dict{$word}[$len] = $definition;
    }
    else
    {
        $dict{$word}[0] = $definition;
    }
}
3
  • 2
    Your entire if/else can be replaced by push @$dict{$word}, $definition. Right now you are copying the array just to compute its length. Commented Jul 18, 2013 at 1:41
  • I got the error message Not an ARRAY reference Commented Jul 18, 2013 at 1:45
  • that's because $dict{$word} doesn't have a value initially, so trying to cast that to an array doesn't work, because it's not an array reference. Commented Jul 18, 2013 at 2:43

1 Answer 1

2

pretty sure this works (can't test right now)

foreach $line (@lines)                               # read line from a text dictionary 
{
    chomp( $line );
    my($word, $definition) = split(/\s/, $line, 2); # 
    $definition =~ s/^\s+|\s+$//g ;                 # trim leading and trailing whitespace

    push @{$dict{$word}}, $definition;

}

(using unshift instead of push will put the new entry on the other side of the other entries)

Sign up to request clarification or add additional context in comments.

2 Comments

Probably ||= [] may be omitted, thanks to autovivification.
Looks like you're right. Updating answer. I like the curlies around the cast, though, as it makes it very clear what's being done.

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.