Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the meaning of the & in threads::shared::share usage in perl?

Tags:

perl

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?

like image 206
rodman10 Avatar asked Dec 30 '25 15:12

rodman10


1 Answers

& 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
like image 85
ikegami Avatar answered Jan 02 '26 09:01

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!