X hits on this document

PDF document

Running and Debugging Perl - page 6 / 30





6 / 30

Chapter 9

use warnings

The warnings pragma changes the way perl produces warnings. Ordinarily, there are a number of warnings that you can turn on and off, categorized into a series of areas: syntactic warnings, obsolete ways of programming, problems with regular expressions, input and output, and so on.

Redeclaring Variables

By default, all warnings are turned off. If you merely say use warnings, everything is turned on. So, for example, without specifying use warnings, the following code will execute without issue:


  • #


    • #

      add 'use warnings;' command here

my $a = 0; my $a = 4;

However, with use warnings specified after the filename comment, here is what perl tells you:

>perl warntest.plx "my" variable $a masks earlier declaration in same scope at warntest.plx line 6. >

What does this mean? It means that in line 6, we declared a new variable $a. If you remember, my creates a completely new variable. However, we already have a variable $a, which we declared in line 5. By re-declaring it in line 6, we lose the old value of 0. This is a warning in the 'misc' category.

Misspelling Variable Names Let's see another common cause of error - misspelling variable names:


  • #


    • #

      add 'use warnings;' command here

my $total = 30; print "Total is now $total\n"; $total += 10; print "Total is now $tutal\n";

Without warnings, we see this:

  • >

    perl warntest2.plx

Total is now 30 Total is now

Why has our variable lost its value? Let's turn on warnings and run this again. Now we get:

  • >

    perl warntest2.plx

Name "main::tutal" used only once: possible typo at warntest2.plx line 8. Total is now 30 Use of uninitialized value in concatenation (.) at warntest2.plx line 8. Total is now


Document info
Document views52
Page views52
Page last viewedMon Oct 24 00:27:35 UTC 2016