FreeKB - Identical subroutine names in Perl (package, namespace)
Identical subroutine names in Perl (package, namespace)

Home > Search


Let's say you want have have two different subroutines with the same name. In this example, both subroutines are called foo.

sub foo {
  print "hello";
}

sub foo {
  print "world";
}

 

You can invoke the foo subroutine.

foo();

 

Which will print the text world.

world

 

So how do we invoke foo and get "hello" to print? This is what package is used for. Consider the following. In this example, the first subroutine is in the "main" package. The second subroutine is in the "child" package. By the way, main is the default package. If you don't specify package main, then package main is assumed. "child" is an arbitrary name. You could use any text you want, even something as silly as package mecalecahimechahinnyho.

package main;
sub foo {
  print "hello";
}

package child;
sub foo {
  print "world";
}

 

Now, we can use the foo subroutine in the main package, like this.

main::foo();

 

Which will print hello.

hello

 

Or in the child package, like this.

child::foo();

 

Which will print world.

world


By the way, "main" and "child" are namespaces.



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 54035 in the box below so that we can be sure you are a human.




Comments