Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define an anonymous scalar ref in Perl?

How do I properly define an anonymous scalar ref in Perl?

my $scalar_ref = ?;

my $array_ref = [];

my $hash_ref = {};

like image 607
tjwrona1992 Avatar asked Sep 09 '25 22:09

tjwrona1992


1 Answers

If you want a reference to some mutable storage, there's no particularly neat direct syntax for it. About the best you can manage is

my $var;
my $sref = \$var;

Or neater

my $sref = \my $var;

Or if you don't want the variable itself to be in scope any more, you can use a do block:

my $sref = do { \my $tmp };

At this point you can pass $sref around by value, and any mutations to the scalar it references will be seen by others.

This technique of course works just as well for array or hash references, just that there's neater syntax for doing that with [] and {}:

my $aref = do { \my @tmp };  ## same as  my $aref = [];

my $href = do { \my %tmp };  ## same as  my $href = {};
like image 155
LeoNerd Avatar answered Sep 12 '25 21:09

LeoNerd