X hits on this document

PDF document

Running and Debugging Perl - page 9 / 30





9 / 30

Running and Debugging Perl

You may see another way of declaring a global, use vars '$var', which does exactly the same as our. our was introduced in Perl 5.6.0 and is recommended for use, wherever backward compatibility isn't an issue.

If use strict applies and you have not used one of these forms of declaration, Perl will not allow you to run the program:


  • #


use warnings; use strict;

my $a = 5; $main::b = "OK"; our $c = 10; $d = "BAD";

The first three variables are fine, but:

>perl strictvar.plx Global symbol "$d" requires explicit package name at strictvar.plx line 9. Execution of strictvar.plx aborted due to compilation errors. >

To fix this, you just need to use one of the above ways of declaring the variable. Here's an important lesson in debugging: don't turn off the warnings – fix the bug. This is especially important when we come to our next cause of problems, references.

Strict on References

One thing novice programmers often want to do is to construct a variable whose name is generated from the contents of another variable. For instance, you're totalling numbers in a file with several sections. Each time you come to a new section, you want to keep the total in another variable. So, you might think you want $total1, $total2, $total3, and so on, with $section pointing to the current section. The problem then is to create a variable out of "total" plus the current value of $section. How do you do it?

Honest answer: You can say ${"total".$section}.

Better answer: Don't do it. In such cases, it's almost always better to use a hash or an array. Here, since the sections are numeric, you'd use an array of totals. It's far easier to say $total[$section]. More generally, if your sections are named, you'd use a hash, $total{$section}.

Why? Well, the most obvious reason is because you know how to use hashes and arrays, and when the question was asked, you didn't know how to construct a variable by name. Use what you know! Don't try and be too clever if there's a simple solution. Constructing these symbolic references, as they are known, can play havoc with any of your variables.

Suppose you're making a variable not out of ${"total".$section} but ${$section} where $section is read from the file. If reading the section name goes horribly wrong, you may have $section become one of Perl's special variables, either causing an error or creating weird behavior later in your program – arrays may suddenly stop working, regular expression behavior may become unpredictable, and so on. This kind of thing is a nightmare to debug.


Document info
Document views58
Page views58
Page last viewedTue Oct 25 22:38:40 UTC 2016