简体   繁体   中英

Using shared hash in Perl

Why I get this error?

Thread 1 terminated abnormally: Invalid value for shared scalar at thr_hash.pl line 8.

use threads;
use threads::shared;
use Data::Dumper;

my %h:shared;

threads->create(sub{
    $h{manager} = {
        name => 'John',
        surname => 'Doe',
        age => 27
    };
})->detach;

sleep 1;

print Dumper \%h;

Use shared_clone() when using a variable (anonymous hash in this case) in an assignment.:

use threads;
use threads::shared;
use Data::Dumper;

my %h:shared;

threads->create(sub{
    $h{manager} = shared_clone({
        name => 'John',
        surname => 'Doe',
        age => 27
    });
})->detach;

sleep 1;

print Dumper \%h;

Output:

$VAR1 = {
          'manager' => {
                         'surname' => 'Doe',
                         'name' => 'John',
                         'age' => 27
                       } 
        };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM