Main Content
Variable Scope Archive - Originally posted on "The Horse's Mouth" - 2004-10-22 07:32:43 - Graham Ellis
One of the vital topics on all our programming courses is that of variable scope. Variable Scope may be defined as the area of a program in which a variable is visible, and how long that variable is accessible for.
Why do I describe variable scope as a vital subject when you can write simple programs in almost any of the languages we teach without any appreciation of the issue? Because it becomes vital as your code grows into a series of blocks - sometimes named (functions in PHP , procs in Tcl , def in Python , subs in Perl , methods in Java ) and sometimes not (for example { to } blocks in Perl, inset blocks in Python). As a new programmer, you might think that all variables should be visible everywhere (this is often know as "default global"), but that's a bad default - the only language that has this default is Perl and that's for historic reasons. It will change at Perl 6!
Why is "default global" a bad default? Because it means that when you combine code from two blocks / files / sources, each must have variables who's names don't conflict with and other name in any other module and in practice that's almost impossible to ensure. Looking at a real-life example, in our household "Charlie" refers to the cat, but in the Royal Family "Charlie" might be used to refer to the Prince of Wales. Let's say that the Royal family comes to visit us (yeah, improbable I know!), and someone says "come here Charlie" .... are they going to get a cat or a prince?
Some other articles
Z203 - Cat and Dog Spring at Well House Manor Day trip to Lancaster Black dog day - and Bobby still seeks his new home In favour of adoption rather than puppy purchase - dogs! Different views of a Welsh Valley - but headed home Crisp morning, fast run Misty Melksham Morning Too many Staffies, too many lurchers Who are we - Lisa, Graham, Gypsy and Billy Exceptionally, I sign a petition - on a life and death issue for Irish dogs Soft furnishings up a Welsh Mountain Red, yellow, green or pink dog? Yellow Dog Project With us for a year already! Lisa is home today ... Challenge for a photographer Black dogs at Halloween Taking the lead, not the dog, for a walk. Postcards from Barmouth Spring 2012 Off to walk the dogs An update on Billy the Greyhound and Gypsy the Lurcher Gypsy and Billy enjoy the snow Happy Christmas ... a Christmas morning walk in Melksham Changes to morning routines I loves Melksham Letting the foster parents know ... too little or too much? No message - just doggy pictures of the new doggy A typical weekend?? Return trip - Dogs Trust, Newbury Rabbit Shelter Contrast in pictures The Land of the Black Labrador Sleeping in on Sunday Can my dog eat potatoes? Doggie Dietary Research, and political sleaze! Bookkeeping ourdog is Greyhound, Staffie and Ginger Cake A better design of mouth Bright Eyes Gypsy says Family Gathering at 404, The Spa The dog is not in trouble Dogs Trust, Dog Show, Newbury Leaping dog, Leaping horse, copyright of old masters Watching the tele Beware - giving copyright away when you upload a picture - Dogs Trust Ski bore ... train bore ... dog bore Learning about Lurchers Also for the eyes of the cat From cat breeder to Cobol to Perl We can offer a room, but we can't operate on a dog Taking the dog for a walk This article Technical Open House Y105 - Functions, Modules and Packages From and Import in Python - where is the module loaded from? Embedding more complex code into a named block Nesting decorators Recursion in Python - the classic example What are callbacks? Why use them? An example in Python What is the difference between a function and a method? Reading command line parameters in Python A good example of recursion - a real use in Python Python - even named code blocks are objects Multiple yields and no loops in a Python generator? Python functions - an introduction to how they work Python varables - checking existance, and call by name or by value? Exception, Lambda, Generator, Slice, Dict - examples in one Python program vargs in Python - how to call a method with unknown number of parameters Optional positional and named parameters in Python Default local - a good choice by the author of Python Static variables in Python? Python timing - when to use a list, and when to use a generator Functions are first class variables in Lua and Python Finding all the unique lines in a file, using Python or Perl Python Packages - groupings of modules. An introduction Static variables in functions - and better ways using objects Passing optional and named parameters to python methods Catching the fishes first? Passing parameters to Python functions - the options you have Returning multiple values from a function call in various languages - a comparison Using an exception to initialise a static variable in a Python function / method Python - some common questions answered in code examples Passing a variable number of parameters in to a function / method Program for reliability and efficiency - do not duplicate, but rather share and re-use Optional and named parameters to Python functions/methods Python - access to variables in the outer scope Global and Enable - two misused words! Good example of recursion in Python - analyse an RSS feed Sample code with errors in it on our web site Optional parameters to Python functions Multiple returns from a function in Python Conversion of OSI grid references to Eastings and Northings Dynamic code - Python Optional and named parameters in Python What to do with a huge crop of apples Anonymous functions (lambdas) and map in Python Sharing variables with functions, but keeping them local too - Python Global - Tcl, PHP, Python Python Script - easy examples of lots of basics Returning multiple values from a function (Perl, PHP, Python) A better alternative to cutting and pasting code Function / method parameters with * and ** in Python It's the 1st, not the 1nd 1rd or 1th. Sludge off the mountain, and Python and PHP Python - A list of methods Recursion in Python Python - function v method Dynamic functions and names - Python Do not duplicate your code Cottage industry or production line data handling methods Python modules. The distribution, The Cheese Shop and the Vaults of Parnassus. Python - block insets help with documentation Python's Generator functions Difference between import and from in Python What is a callback? Code and code maintainance efficiency Call by name v call by value Lambdas in Python Python generator functions, lambdas, and iterators Distance Learning This article T207 - Procedures and Variable Scope Accessing variables across subroutine boundaries - Perl, Python, Java and Tcl Sharing lots of values in Tcl without having lots of global declarations Passing back multiple results in Tcl - upvar and uplevel Tcl - Some example of HOW TO in handling data files and formats Passing a variable number of parameters in to a function / method Global and Enable - two misused words! Tcl - uplevel to run code at calling level Tcl - passing arrays and strings in and back out of procs Calling procs in Tcl and how it compares to Perl Tcl - global, upvar and uplevel. A better alternative to cutting and pasting code Do not duplicate your code Functions and commands with dangerous names Call by name v call by value Passing arrays to procs in Tcl This article P209 - Subroutines in Perl Learning to use existing classes in Perl Perl functions such as chop change their input parameters Separating groups of variables into namespaces Passing a variable number of parameters in to a function / method Fresh Perl Teaching Examples - part 2 of 3 Do not copy and paste code - there are much better ways Efficient calls to subs in Perl - avoid duplication, gain speed Romeo and Julie Seven new intermediate Perl examples Daisy the Cow and a Pint of Ginger Beer Perl - Subs, Chop v Chomp, => v , Global - Tcl, PHP, Python Calling procs in Tcl and how it compares to Perl Returning multiple values from a function (Perl, PHP, Python) A better alternative to cutting and pasting code Perl - $_ and @_ Do not duplicate your code Changing @INC - where Perl loads its modules Packages in packages in Perl Where do Perl modules load from Call by name v call by value This article J706 - Objects and Classes Objects - from physical to virtual or abstract - Java Binomial Coefficient (Pascal Triangle) objects in Java Calculation within objects - early, last minute, or cached? Defining a static method - Java, Python and Ruby Looking inside Java classes - javap and javadoc When should I use OO techniques? Introduction to Object Oriented Programming Long, Longer, Longest in Java First Class Java. First step and moving forward. An example of Java Inheritance from scratch A better alternative to cutting and pasting code Class, static and unbound variables This article H105 - Functions Coding efficiency - do not repeat yourself! Passing a variable number of parameters in to a function / method Improving your function calls (APIs) - General and PHP Adding extensions to PHP Open Source applications - callbacks Static variables and ampersands in PHP A variable number of arguments in a PHP function Global - Tcl, PHP, Python Static variables in PHP Clean my plate, but keep my wine bottle. (PHP; Static) is there a lookup function in php? Returning multiple values from a function (Perl, PHP, Python) A better alternative to cutting and pasting code PHP - static declaration Global, Superglobal, Session variables - scope and persistance in PHP A lazy programmer is a good programmer Do not duplicate your code Don't repeat code - use loops or functions Functions and commands with dangerous names Code and code maintainance efficiency Passing information into and out of PHP functions Call by name v call by value There is a function in PHP to do that This article