views:

62

answers:

2

In Perl 5.10.1:

#!/usr/bin/perl

my @a = (1, 2, 3);
my $b = \@a;
print join('', @{$b}) . "\n";
@a = (6, 7, 8);
print join('', @{$b}) . "\n";

This prints 123 then 678. However, I'd like to get 123 both times (i.e. reassigning the value of @a will not change the array that $b references). How can I do this?

+4  A: 

Make a reference to a copy of @a.

my $b = [ @a ];
mobrule
Great, thanks. Similarly, `my $b = { %a };` works with hashes. I notice that no similar trick is needed for code references though - why is that?
jnylen
Are you trying to modify the coderef?
Daenyth
I'm basically doing `my $a = sub { ... }; my $b = $a;`. Then when I reassign `$a` to a different coderef, `$b` doesn't change (which is the behavior I want; I was just wondering why that happens).
jnylen
Because $b isn't a reference to $a. When you do `$a = sub { ... }` later on, you're creating a new coderef and putting it in $a -- which doesn't replace the thing that $b points to. The difference here is that a coderef is always a ref -- you never work with non-ref "code values".
hobbs
Note that if @a contains references, this will still have a reference to the original data in $b. For complex data structures you should use something like Storable's clone.
Oesor
A: 

Bretter use dclone for deep cloning of references pointing to anonymous data structures.

gerrit