Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

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"};

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>