next up previous contents index
Next: Local and global variables Up: Variables Previous: Random values   Contents   Index


Declaring variables

We now discuss an aspect of Perl called variable declaration. Unlike some other languages like C or Java, Perl by default doesn't force you to declare variables in a program, so that you can introduce variables at will:
   $count = 0;
   print $count;
This however can make for hard-to-track-down bugs; for example, suppose you have
  $flavor = 'cherry';
  ........   # 2300 lines later
  print qq{My favourite flavour is $flavour.};
This last line will print out My favourite flavour is ., whereas you might have expected it to be My favourite flavour is cherry. The problem here is that you assigned a value of cherry to the variable $flavor, but later used a different variable $flavour in the print statement.

To help in this, and many other common slips, Perl offers a pragma called strict which forces you to declare all variables (and some other things) you use. To use this, you put use strict; as the first line of your program, and then declare all variables you use with a my declaration. The above example would be written as

  use strict;
  my $flavor = 'cherry';
  .........   # 2300 lines later
  print qq{My favourite flavour is $flavour.};
When you try to run this program, it will die with an error message saying that the variable $flavour in the line using the print statement wasn't declared, which will probably be enough for you to recognize that you made a typo.

Certain special variables provided by Perl, such as, as we shall see later, $_ for a loop variable or @_ for a subroutine argument list, cannot be declared by my; for this, you can use local instead.

To also help you in debugging, Perl offers a warning pragma which will point out any (what Perl considers as) bad programming practices. For example, consider

use strict;
use warnings;
my $count;
print "\$count is $count\n";
Here, the variable $count is declared, so the program will run with use strict;, but the use of use warnings; will produce a message when the program is run:
use of uninitialized value in concatenation (.) or string
What this means is that you're using a variable in a context where it's normally expected to have a value. Warnings aren't fatal errors - the programs will still run - but they can alert you to potential pitfalls in your program.

Subsections
next up previous contents index
Next: Local and global variables Up: Variables Previous: Random values   Contents   Index