Perl Tutorial

Page 105

5.8 Leftovers ”

93

Package, or namespace, is a mechanism to minimize variable name clashes. • • •

• •

Variables of the same name may exist concurrently in each package. Variables not within the extents of any packages belong to the main package. Package variables are referenced by qualifying the variable name with the package name, followed by ::. * Defaults to the main package if :: is present but the package name is not specified. * Defaults to the current package in effect if both the package name and :: are absent. Package variables are resolved from the symbol table. Each package may have multiple BEGIN blocks which are executed at compile time.

An association that is lexically scoped is visible from the point in the environment where it is established and all environments that exist within the extents of the current environment, until the end of the current environment. my variables are lexically scoped.

The scope of an association that is dynamically scoped depends on the call stack. A dynamically scoped association exists as long as the current environment is not destroyed. local variables are dynamically scoped.

Web Links 5.1

Coping with Scoping http://perl.plover.com/FAQs/Namespaces.html

Questions A.

In Example 3.7 I presented a binary search program to check if a user-specified integer exists in the list of 100 randomly-generated integers. Introduce the following changes to the program:

? ? ? ?

convert it from iterative to recursive approach; only the search routine is sufficient. You are not required to write the parts which accept user input and generate integers in random; use lexical variables wherever appropriate; the search routine should be placed inside a package with name Search, in an external file “binarysearch recursive.pl”;

There should be at least a binarySearch() subroutine which is in the Search package (namespace), which can be invoked as follows:

require ’binarysearch_recursive.pl’; my $exists = Search::binarySearch(@array, $integer); where @array is any array containing a list of integers, $integer is the integer to search for, and $exists is 1 if the integer is found, undef otherwise. You may save the number of comparisons taken to reach a conclusion as a package variable $numSteps in the Search package that can be accessed directly or through a subroutine.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.