Main Content

Accessing variables across subroutine boundaries - Perl, Python, Java and Tcl

Archive - Originally posted on "The Horse's Mouth" - 2015-01-18 10:14:18 - Graham Ellis

In a perfect programming world, code is broken into named blocks (methods, functions, subroutines, classes, procedures, commands, modules, packages etc) and data is passed around between the blocks purely as parameters and return values. And variables are local to the block in which they're used. This means that each block is independent testable and makes for robust and re-usable code.

It's not a perfect programming world, though!

Most languages have the concept of global variables (which you should use with extreme care!). Tcl offers you uplevel and upvar which let you work in your calling (or a higher) namespace from within a proc (and it's a vital part of the language too) and there are a number of other ways that elements can be shared. Example - [here].

In Python, variables can be read (read only) within a method from the surrounding / calling scope - very useful for passing in . For example (from [here]), the following code
  def bynumber (home, away):
    fred = cmp(count[home],count[away])
    if fred == 0: fred = cmp(home,away)
    return fred

In which the count array is read in the sort function, even though it's not global

In Java inner classes to a little of the same - see [here] - although in truth that's more one class shared within another.

In Perl variable default to being global (yuk!) and indeed we usually write
  use strict;
on all but the shortest of programs and top level codes in order to reverse this design . You can use my to request variables to be scoped to the block in which they are defined (and note that for the purpose of this article, they are visible within inner subroutines too), and you can use our to request a variable has the global scope, even if you are being strict. The real purpose of strict is to avoid the accidental / careless / thoughless creation of global variables, not to stop you doing it in those few right cases. Example of Perl's scoping inc