Being Strict with Your Variables


In the last chapterthe use of modules to implement pragmas was discussed. One very useful pragma to aid in debugging is use strict;. This statement does two things:
  • Forces you to use the my() function to declare all variables. When all variables have a local scope, you avoid problems associated with unintentionally changing the value of a variable in a function.
  • Ensures that you can't use accidental symbolic dereferencing. This topic was not covered in Chapter on References, because it is relatively advanced. If you use the dereferencing techniques shown in that Chapter you won't need to worry about this requirement.

  •  
    When the strict pragma is used, your script will not compile if the preceding two rules are violated. For example, if you tried to run the following lines of code, debug3.pl
    use strict;

    $foo = { };

    $bar = 5;

    print("$foo/n");

    print("$bar/n");

    you would receive these error messages:
    Global symbol "foo" requires explicit package name at test.pl line 3.
    Global symbol "bar" requires explicit package name at test.pl line 4.
    Global symbol "foo" requires explicit package name at test.pl line 6.
    Global symbol "bar" requires explicit package name at test.pl line 7.
    Execution of test.pl aborted due to compilation errors.

    In order to eliminate the messages, you need to declare $foo and $bar as local variables, like this, debug4.pl:
    use strict;

    my($foo) = { };

    my($bar) = 5;

    print("$foo/n");

    print("$bar/n");

    The my() function makes the variables local to the main package.
    In the next section, you see how to use the debugger to step through your programs.

    좋은 웹페이지 즐겨찾기