5.5 Subroutine Scope

     

Just like variables , subroutine names are simply entries in a symbol table or lexical scratchpad. So, all subroutines live in a particular scope, whether it's lexical, package, or global scope.

5.5.1 Package-Scoped Subroutines

Package scope is the default scope for subs. A sub that is declared without any scope marking is accessible within the module or class where it's defined with an unqualified call, like subname( ) , and accessible elsewhere with a fully qualified call using the Package:: Name ::subname( ) syntax. [5]

[5] Certain levels of strictness may require the fully qualified name everwhere.

 module My::Module {   sub firstsub ($param) { . . . }   sub secondsub {     mysub('arg'); # call the subroutine   } } module Other::Module {   use My::Module;   sub thirdsub {      My::Module::firstsub('arg');   } } 

This example declares two modules, My::Module and Other::Module . My::Module declares a subroutine firstsub and calls it from within secondsub . Other::Module declares a subroutine thirdsub that calls firstsub using its fully qualified name.

5.5.2 Lexically Scoped Subroutines

Subroutines can also be lexically scoped, just like variables. A my ed subroutine makes an entry in the current lexical scratchpad with a & sigil. Lexically scoped subs are called just like a normal subroutine:

 if $dining {     my sub dine ($who, $where) {          . . .      }     dine($zaphod, "Milliways"); } # dine($arthur, "Nutri-Matic");  # error 

The first call to the lexically scoped dine is fine, but the second would be a compile-time error because dine doesn't exist in the outer scope.

The our keyword declares a lexically scoped alias to a package scoped subroutine (it has an entry both in the symbol table of the current package and in the current lexical scratchpad). This is useful under certain levels of strictness.

 if $dining {     our sub pay ($when, $what) {          . . .      }     pay($tuesday, "hamburger"); } 

5.5.3 Globally Scoped Subroutines

Globally scoped subroutines are visible everywhere, unless they're overridden by a lexical or package scoped subroutine of the same name. They are declared with the * symbol before the name of the subroutine:

 sub *seen_by_all ($why, $how) { . . . } 

Most built-ins will be globally scoped.



Perl 6 and Parrot Essentials
Perl 6 and Parrot Essentials, Second Edition
ISBN: 059600737X
EAN: 2147483647
Year: 2003
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net