Re: does double array dereferencing make a copy?



Ian Zimmerman wrote:
# Must protect ourself against corruption as the hash contains refs to the
# SV's in the list, if the user modifies this list we are really screwed :-

[ @{$me->{'mail_hdr_list'}} ];
}

How does that protect him? Doesn't the reference returned from the subroutine
again point to the original "fragile" array?

No.

In my own words:

my @foo = qw(bar baz);
my $fooref = \@foo;
my $foo2ref = [ @{$foo} ];
${$foo2ref}[0] = 'blech';
$foo[0] == 'blech'; # Yes or no?

Why are you asking? Why didn't you just try it yourself? (After
correcting the == vs eq problem, of course).

$ perl -le'
my @foo = qw(bar baz);
my $fooref = \@foo;
my $foo2ref = [ @{$foo} ];
${$foo2ref}[0] = q{blech};
print "Yes" if $foo[0] eq q{blech}; # Yes or no?
print \@foo, "\t", $fooref, "\t", $foo2ref;
'
ARRAY(0x100564) ARRAY(0x100564) ARRAY(0xf0b10)

$fooref is a reference to @foo. $foo2ref is a reference to a new array
that was intially populated with the values from @{$foo}.

This is analogous to doing:

my @a1 = qw/bar baz/;
my @a2 = ( @a1 );

@a2 now has the same initial values as @a1, but changes to one have no
effect on the other.

\ takes a reference to an actual named array.
[ ] creates a new anonymous reference.

Paul Lalli


.



Relevant Pages