It's a good point, and a good thought, but it doesn't help (much) unfortunately.
Whilst disabling the prototype allows me to pass an anonymous hash directly to share(), it still causes any contents in that hash to be discarded.
It does mean that you can share and assign an empty anonymous hash directly into the parent shared hash, which avoids the temp var at the slight inconvenience of obscurity, but it still doesn't make up for the lack autovivification :(
#! perl -slw use strict; use Data::Dumper; use threads; use threads::shared; my %hash1 : shared; ## Disabling the prototype allows the call ## to accept an anonymous hash $hash1{A} = &share( { 1 => 'b' } ); ## But inspecting the results on a different thread ## show that the contents of the hash were discarded. async{ print Dumper \%hash1; }->detach; =output $VAR1 = { 'A' => {} }; =cut sleep 2; ## Give the async thread a timeslice my %hash2 : shared; ## This also happens if you accomodate the prototype ## using an intermediate temp variable. my $temp = { 1 => 'b' }; share $temp; print Dumper $temp; ## Anon. hash shared, but emptied. =output $VAR1 = {}; =cut ## The only way I had found to do it is: my $temp2 = {}; ## Create a temp var ref to the anon. hash share $temp2; ## share the temp var. $temp2->{1} = 'b'; ## populate the 'anon' hash print Dumper $temp2; ## Now the contents are available =output $VAR1 = { '1' => 'b' }; =cut ## Then assign the shared 'anon' hashref ## To the shared hash. $hash2{A} = $temp2; async{ print Dumper \%hash2 }->detach; ## Now we see it =output $VAR1 = { 'A' => { '1' => 'b' } }; =cut sleep 2; ## Give the async thread a timeslice ## However, by bypassing the prototype you can avoid a step my %hash3 : shared; $hash3{A} = &share( {} ); $hash3{A}{1} = 'b'; async{ print Dumper \%hash3; }->detach; =output $VAR1 = { 'A' => { '1' => 'b' } }; =cut sleep 2; ## Give the async thread a timeslice
In reply to Re^3: Declaring/Assigning thread shared vars
by BrowserUk
in thread Declaring/Assigning thread shared vars
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |