CGI and Perl

Lexical Scoping

The new my() operator enables you to declare variables that are truly lexically scoped. Previously, the closest you could get to a lexical variable was with local(). The my() variables are visible only within the current block (within a set of curly braces) and go out of scope immediately after exiting the block. The following example illustrates their use:

$foo = "I\'m foo in a global context\n";
 print $foo;
 {  # the curlies open a new lexical context (block)
     my $foo = "But I\'m bar in this short lexical context\n";
     print $foo;
 } # lexically scoped $foo goes out of scope here
 print $foo;
 # prints:
 I'm foo in a global context
 But I'm bar in this short lexical context
 I'm foo in a global context

The my() variable is used extensively in the modules that you'll explore in this tutorial. See PERLVAR for complete details on all types of Perl variables, including lexical variables.

References

Standard Perl scalars can now be used to refer to other data types. References act much like pointers in C. In the general sense, they simply refer to other data types. When a reference is blessed into a package, it becomes a Perl Object, and can be used to invoke the methods of its package (or class), as well as to access the instance variables of the class, something akin to C++ references.

Because we'll explore the references in depth later in this chapter, I'll defer most of the examples, and a complete description of them until that time. I'll also explain how the bless() operator works at that time. The reference datatype is also used extensively in the examples.

Data Structures

Nested data types and other data structures are now possible, using references. You'll also learn about this topic later when we look at references in depth. A simple example that implements an array of arrays follows:

@foo = ( 1, 2, 3);
 @bar = ( 4, 5, 6);
 @arrayref = (\@foo, \@bar);
 print "The third element of \@foo is $arrayref[0][2]\n";
 # prints: The third element of @foo is 3

Here, I specify the zero'th element of @arrayref, which is an array of references to arrays, and then use it to dereference the third element of @foo. @arrayref actually looks and feels just like a two-dimensional array, but it's important to understand that it isn't.

Perl does not support multidimensional arrays. All arrays are still flat. By using references, however, you can emulate multidimensional arrays and build up complex data structures. See PERLDSC for a compendium on Perl data structures.