如何检查perl OO代码中的未定义键?

eve*_*box 2 perl

我有use strict;use warnings;我的perl脚本;

但无法找到此错误:

sub new {
     #....
     my $self={};
     $self->{databas}="..."; # 'e' is missing
     #....
}

sub foo {
    my $self=shift;
    print $self->{database}; # undef
 }
Run Code Online (Sandbox Code Playgroud)

我花了好几个小时才发现该数据库被误导了sub new.

use strict;use warnings; 没有帮助.

我怎样才能避免这个错误?

dax*_*xim 8

使用Hash :: Util限制/锁定哈希值.


或者,使用Moose来描述您的类,使拼写错误的属性成为运行时错误.

package MyClass;
use Moose;
has 'database' => (isa => 'Str', is => 'rw', default => 'quux');

sub foo {
    my ($self) = @_;
    $self->database; # returns quux
    $self->databas;  # Can't locate object method "databas" via package…
Run Code Online (Sandbox Code Playgroud)