Mix assignment and reference aliasing with declared_refs

Perl v5.26 adds the experimental declared_refs feature that expands on the experimental refaliasing feature from v5.22. As with all experimental features, this may change or disappear according to perlpolicy.

The refaliasing allows you to alias a named variable to a reference (even if that reference comes from a named variable). You could write that as either of these forms:

use v5.22;
use feature qw(refaliasing);
no warnings qw(experimental::refaliasing);

\my @new = \@old;

my @new;
\@new = \@old;

In the first, you declared and assign in the same statement. The reference operator (\) comes before the my. In the second, you declare the new variable in one statement then alias in another.

The new declared_refs feature lets you move the reference operator to after the declarator (the my):

use v5.26;
use feature qw(refaliasing declared_refs);
no warnings qw(experimental::refaliasing declared_refs);

my \@new = \@old;

This means that list assignments with a mix of ref aliasing and conventional assignments are now possible. This mix is not possible with just the v5.22 feature:

use feature qw(refaliasing declared_refs);
no warnings qw(experimental::refaliasing experimental::declared_refs);

my @cats = qw( Buster Ginger );
my %pets = (
	'Buster' => 'cat',
	'Ginger' => 'cat',
	'Addy'   => 'dog',
	'Nikki'  => 'dog',
	);

my( $n, $m, \@y, \%z ) = ( 'Addy', 'Nikki', \@cats, \%pets );

This still doesn’t get you to ref aliasing in subroutine signatures but it’s a step closer to what you need for that.

One thought on “Mix assignment and reference aliasing with declared_refs”

Comments are closed.