J
John
Dear listers,
I have just started on perl and I have a question about if the thing I
copy is copy the value itself or I am copying the refence.
Can you help me with that?
The code is writen below.
My question is if I (as I understand) copy the values of @a into @b
and then I change the values for @a (on the subroutines) and print
then back. Why @b is altered?
If this is the normal behavior,
Why $st1 and $st2 do look to have the same behavior?
What I am missing?
Thanks for your advise.
John
#the code################################
use strict;
my $st1="abcdefabcdef";
my @a = ( [qw(1 2 3 4 5 6)],
[qw(2 4 6 8 10 12)],
[qw(3 5 7 9 13 15)]
);
my @b = @a;
print $a[1][2],"\n"; # before to do anything PRINT 6
print $a[1][3],"\n"; # before to do anything PRINT 8
pe(\@a); # call the module
print $a[1][2],"\n"; # this value has changed PRINT 88
print $a[1][3],"\n"; # this has changed too PRINT 55
print $b[1][3],"\n"; # but why this has changed is is reffered to
# another array??? WHY PRINT 55?????
# if this is the normal behavior... read down
print "\n";
my $st2= $st1;
$st2 =~ tr/abcdef/123456/;
print "$st1\n"; # why in this case we change one and the
print "$st2\n"; # other remains as it was?
sub pe{
my ($inner1)= @_;
$inner1->[1][2]=88;
per($inner1);
}
sub per{
my ($inner2)=@_;
$inner2->[1][3]=55;
}
and the result is:
6
8
88
55
55
abcdefabcdef
123456123456
I have just started on perl and I have a question about if the thing I
copy is copy the value itself or I am copying the refence.
Can you help me with that?
The code is writen below.
My question is if I (as I understand) copy the values of @a into @b
and then I change the values for @a (on the subroutines) and print
then back. Why @b is altered?
If this is the normal behavior,
Why $st1 and $st2 do look to have the same behavior?
What I am missing?
Thanks for your advise.
John
#the code################################
use strict;
my $st1="abcdefabcdef";
my @a = ( [qw(1 2 3 4 5 6)],
[qw(2 4 6 8 10 12)],
[qw(3 5 7 9 13 15)]
);
my @b = @a;
print $a[1][2],"\n"; # before to do anything PRINT 6
print $a[1][3],"\n"; # before to do anything PRINT 8
pe(\@a); # call the module
print $a[1][2],"\n"; # this value has changed PRINT 88
print $a[1][3],"\n"; # this has changed too PRINT 55
print $b[1][3],"\n"; # but why this has changed is is reffered to
# another array??? WHY PRINT 55?????
# if this is the normal behavior... read down
print "\n";
my $st2= $st1;
$st2 =~ tr/abcdef/123456/;
print "$st1\n"; # why in this case we change one and the
print "$st2\n"; # other remains as it was?
sub pe{
my ($inner1)= @_;
$inner1->[1][2]=88;
per($inner1);
}
sub per{
my ($inner2)=@_;
$inner2->[1][3]=55;
}
and the result is:
6
8
88
55
55
abcdefabcdef
123456123456