Recently, I'm trying to use threads::shared to share some data between threads, and I was confused by the usage of $var = &share([]);
in perldoc, what's the effect of the &
before share
?
&
tells Perl to ignore the prototype.
share
is documented to accept a scalar, an array or a hash.
share( $scalar_to_share )
share( @array_to_share )
share( %hash_to_share )
But it's impossible to pass arrays and hashes to subs. So what's going on?
share
has a prototype (\[$@%]
) which changes how the call is made. Rather than evaluating the argument list as usual, a reference to the provided variable is passed instead.
share( $scalar_to_share ) # Equivalent to `&share( \$scalar_to_share )`
share( @array_to_share ) # Equivalent to `&share( \@array_to_share )`
share( %hash_to_share ) # Equivalent to `&share( \%hash_to_share )`
What if you want to provide a reference to an anonymous array? You can't just pass a reference, since that would share the scalar.
my $ref = [];
share( $ref ); # XXX Would share `$ref` instead of the array.
As documented, you can simply bypass the prototype.
my $ref = [];
&share( $ref ); # ok
Conveniently, share
returns its argument.
my $ref = &share( [] ); # ok
You could also provide the array required by the prototype by dereferencing the reference.
my $ref = share( @{ [] } ); # ok
my $ref = share( []->@* ); # ok