4

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?

1
  • Obligatory warning: Do not use variables named $a or $b in general Perl code. $a and $b are globals used by the sort function and they will be overwritten if sort gets called by your code or by any module it uses. (Yes, I realize that declaring them lexically (with my) sidesteps that because you're not using the global version then, but it's still asking for trouble to use $a or $b.) Commented Jun 25, 2010 at 10:22

2 Answers 2

3

Make a reference to a copy of @a.

my $b = [ @a ];
Sign up to request clarification or add additional context in comments.

4 Comments

Great, thanks. Similarly, my $b = { %a }; works with hashes. I notice that no similar trick is needed for code references though - why is that?
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).
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".
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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.