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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值