C/C++教程

Perl - use strict

本文主要是介绍Perl - use strict,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Perl - use strict

Where to use?

Condition 1: too much lines in your script;
Condition 2: can not find out the reason for error.

Why to use?

Reason 1: help you to find out some easy errors like spelling mistakes; (eg. you claimed ‘apple’ but you used ‘aple’)
Reason 2: force you to minimize the use range of the variables. (It will force you to define the local variable)

How to use?

Step 1: use strict;
Step 2: use ‘my’ to define variable.
Usually error 1: Global symbol “$xxx” requires explicit package name at …
Usually error 2: Server Error - please check ‘error logs’ or use CGI::Carp pakage.
Step 3: some examples.

#!use/bin/perl
use strict;

# example 1
my $string = "hello world";
my @array = qw(ABC DEF);
my %hash = (A=>1, B=>2);

# example 2
foreach my $name (@names){
    print "Name: $name\n";
}

# example 3
my $number = 0;
foreach my $digit (@digits)
    $number = 10== $number + $digit;
}
print "Number: $number\n";

# example 4
sub my_sub {
    my ($arg1, $arg2) = @_;
    print "Arg1: $arg1 Arg2: $arg2\n";
}

# example 5
$sth->bind_columns(\my ($field1, $field2));
while ($sth->fetch) {
    print "F1: $field1 F2: $field2\n";
}

Extension

What is ‘warnings’?

# In Perl 5.6+
use strict;
use warnings;

# In Perl 5.6- (usually use)
#!usr/bin/perl -w

# other method
# set $^W (if $^w not in BEGIN{}, useless)
$^W = 1;
# or
BEGIN{$^W = 1}
# you can limit the range of $^W
# 1
sub add_two_numbers_which_might_be_undef {
    # 参见 'perldoc perllexwarn' 
    # 因为最好是只在你希望的地方禁止掉warning
    no warnings "uninitialized";
    $_[0] + $_[1];
}
# 2
sub add_two_numbers_which_might_be_undef {
    local $^W;
    $_[0] + $_[1];
}

或者,你应像前面例子中声明 '$number’一样初始化变量。

你还可以参阅Ovid的妙文use strict’ is not Perl

以及(Wog指出的):Use strict warnings and diagnostics和Use strict warnings and diagnostics or die.

取自"http://wiki.perlchina.org/index.php/Use_Strict_And_Warnings"

这篇关于Perl - use strict的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!