5
# thread::shared only allws a single level of shared structure
# needs a explicit hash creation for nested data structures
my %counts     : shared = ();

foreach my $state (%known_states) {
    # COUNTS
    unless (exists $counts{build}) {
        my %cb : shared;
        $counts{build} = \%cb;
    }
    $counts{build}{$state} = 0;

}

Right now, I have to do something like the above where I have to explicitly create a hash reference for each sub-level hash.

Is there a better way of doing it?

P.S. if I don't create a hash ref then I get an "Invalid value for shared scalar" error since I am trying to use it as a hash.

1 Answer 1

6

Autovivification makes

$counts{build}{$state} = 0;

behave like

( $counts{build} //= {} )->{$state} = 0;

For readability, let's make it two lines

$counts{build} //= {};
$counts{build}{$state} = 0;

But like you said, we need a shared hash.

$counts{build} //= &share({});
$counts{build}{$state} = 0;

You could add the following to make sure you don't accidentally vivify an unshared variable:

no autovivification qw( fetch store exists delete );
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.