Oct 132010
Is Perl pass by reference or pass by value?
Answer:
(Edit: Thanks Matt for the feedback, I have updated the answer.)
It depends on how your function is implemented
See the code below:
package Dog;
sub new {
my ($class, $name) = @_;
my $self = { "name" => $name };
bless $self, $class;
return $self;
}
// Pass by value
sub Foo {
my $d = shift;
$d = new Dog("Another");
}
// Pass by reference
sub Bar {
$_[0] = new Dog("Another");
}
my $d = new Dog("Peter");
Foo($d); // Pass by value, $d not changed, so it print out "Peter"
print $d->{"name"};
Bar($d); // Pass by reference, $d is changed, so it print out "Another"
print $d->{"name"};