|
|
|
Who is this for
This article is for those who want to learn how to define and use functions in packages What you need to know Introduction This month, we will see how you can use packages. Functions We can create functions within packages to allow us to manipulate variables within the package. Although you can manipulate package variables outside of the package, it is 'cleaner' to manipulate these within the package. Keeping this rule in mind will be useful when we discuss about object-oriented programming in Perl. A sample package can look like this: package street; sub new { my $self = {}; # create a hash reference } } The package has one function called new. You can call the function whatever you want but to conform to standards, we will call this new. And a sample script to use this package is this: $a = street->new('Pembroke'); # create new street package The first line of the script calls the new function of the street package. The first thing the new function does is to allocate a variable ($self) that refers to a HASH. ($self is a hash reference). The next line assigns the parameters passed to the function to the $class and $name variables respectively. The first parameter passed to a new is ALWAYS the package name, in this case street. The next line assigns the value in the $name variable to the name element pointed to by the $self hash reference. The last line in the function returns the value of the variable - $self. On return to the main package, the result is stored in the $a variable. The next line prints the variable type referred to by the variable $a. Since $a has the contents of $self from the package, it refers to a HASH. When you run this script, the result will be: Package Name: HASH Now for the interesting part Go To Page: 1 2
The copyright of the article Perl Packages - Part 4 (Functions) in Perl is owned by . Permission to republish Perl Packages - Part 4 (Functions) in print or online must be granted by the author in writing.
|
|
|
|
|
|
|
|