Search code examples
perlshallow-copyarrayref

Shallow copy reference into variable in Perl


In Perl, you can assign to a variable a reference to another variable, like this:

my @array = (1..10);
my $ref = \@array;

And, as it is a reference, you can do something like this and both variables will be affected:

push @array, 11;
push @$ref, 12;

and both variables will contain 1..12, because they both point to the same space.

Now, I'd like to know if there is any way you can do the same thing, but starting with a ref and later assigning that reference to a plain variable. For example:

my $ref = [1..12];
my @array = # something here that makes @array point to the same space $ref contains

I know I can just assign it like this:

my @array = @$ref;

but, that's a copy. If I alter $ref or @array, those will be independent changes.

Is there some way to make @array point to the same variable as $ref?


Solution

  • Four ways:

    • our @array; local *array = $ref;
    • \my @array = $ref; (Experimental feature added to 5.22)
    • use Data::Alias; alias my @array = @$ref;
    • Using magic (e.g. tie my @array, 'Tie::StdArrayX', $ref;)

    But of course, the sensible approach is to do

    my $array = $ref;
    

    and use @$array instead of @array.



    Aforementioned Tie::StdArrayX:

    package Tie::StdArrayX;
    use Tie::Array qw( );
    our @ISA = 'Tie::StdArray';
    sub TIEARRAY { bless $_[1] || [], $_[0] }