Have a look at this piece of code:
my @arr = (1, 2);
my $ref = \@arr;
my @s = @$ref;
push @s, 4;
print join(", ", @arr) . "\n";
Unexpectedly, the output is “1, 2”. What happened? How come I got two different arrays (@s is (1,2,4))?
Of course I get “1, 2, 4” if I write, before the output, something like this:
$ref = \@s;
@arr = @$ref;
But that seems rather clumsy.
I’m used to other OOP languages, in which such a thing wouldn’t happen – an object can me modified, regardless of its references.
So can anyone please help me with that?
makes a copy of the referenced array. After that,
@sand@arrare unrelated arrays that just happen to have the same contents (for a while).If you want to modify the referenced array, you have to use it directly, e.g.:
There’s also the Data::Alias module, which (I think) lets you do what you’re asking for. But there’s deep magic involved there, and I’ve never used it myself.