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?


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

  2 Responses to “Is Perl pass by reference or pass by value?”

  1. Actually, that is incorrect. Perl is a pass by reference, but when it does assignments it does by value. its really kindof screwy.

    See the following code:


    my $str = "hello";

    print "String: $str\n";

    sub foo {
    $_[0] = "foo";

    if it was pass by value, the printout would still be "String: hello", but instead your printout is going to be "String: foo";

    so if you want the foo method to not modify the thing outside the foo method it should be like this:

    sub foo {
    my $x = $_[0]; #(or shift, or whatever method you want)
    $x = "foo";

  2. @Matt, Thanks for your correction, I have updated the answer.

 Leave a Reply



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>