Friday, 27 July 2012

Getting Deeper Into Perl


$ perldoc perlop ( perlop - Perl operators and precedence)..

Variable Scoping in Perl:

my provides lexical scoping; a variable declared with my is visible only within the block in which it is declared.

Blocks of code are hunks within curly braces {}; files are blocks.

Use use vars qw([list of var names]) or                       our ([var_names]) to create package globals.

local saves away the value of a package global and substitutes a new value for all code within and called from the block in which the local declaration is made.

Use the package operator to set the current package.

Implicitly, there's a package main; at the top of your scripts; that is, unless you explicitly declare a different package, Variables that live in a package are reasonably called "package globals", because they are accessible by default to every operator and subroutine that lives in the same package

Using packages makes accessing Perl variables sort of like travelling in different circles.

To satisfy strict 'vars' (the part of strict that enforces variable declaration), you have two options; they produce different results, and one is only available in perl 5.6.0 and later:
  1. our ($foo, $bar) operator (in perl 5.6.0 and above) declares $foo to be a variable in the current package.
  2. use vars qw($foo $bar) (previous versions, but still works in 5.6) tells 'strict vars' that these variables are OK to use without qualification in the current package.
One difference between our and and the 'older' use vars is that our provides lexical scoping (more on which in the section on my below).

Another difference is that with use vars, you are expected to give an array of variable names, not the variables themselves (as with our). Both mechanisms allow you to use globals while still maintaining one of the chief benefits of strict 'vars'

my (and a little more on our)  lexical scoping:

1. Variables declared with my are not globals, A main use of my is to operate on a variable that's only of use within a loop or subroutine, 

  • A my variable has a block of code as its scope (i.e. the places in which it is accessible).
  • A block is often declared with braces {}, but as far as Perl is concerned, a file is a block.
  • A variable declared with my does not belong to any package, it 'belongs' only to its block
  • Although you can name blocks (e.g. BEGIN, with which you may already be familiar), you can't fully qualify the name of the block to get to the my variable.
  • File-level my variables are those which are declared in a file outside of any block within that file.
  • You can't access a file-level my variable from outside of the file in which it is declared (unless you explicitly return it from a subroutine, for example).

  • local  (dynamic scoping)

No comments:

Post a Comment