Bootstrap FreeKB - Perl (Scripting) - Identical subroutine names (package, namespace)
Perl (Scripting) - Identical subroutine names (package, namespace)

Updated:   |  Perl (Scripting) articles

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 used. "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.




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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