1

I have a Perl class which is a based on a blessed hashref ( https://github.com/kylemhall/Koha/blob/master/Koha/Object.pm )

This is a community based project, with many developers of varying skill.

What I've seen is some developers accidentally using our objects as hashrefs. The actual data is not stored in the blessed hashref, but in a dbic object that is stored in the hashref ( in $self->{_result} ). When the dev tries something like $object->{id} perl doesn't complain, it just returns undef, as would be expected.

What I'd like to do is to either A) Make the script explode with an error when this happens B) Allow the use of the hashref syntax for setting / getting values in the dbic objects stored in $self->{_result}

I tried using:

use overload '%{}' => \&get_hashref;

but when I do this, get_hashref is called any time a regular method is called! This makes sense in a way, since the object itself is a hashref. I'm sure this has something to do with the Perl internals for blessed hashrefs as objects.

Is what I'm trying to accomplish even possible?

4

2 回答 2

5

我建议使用基于标量或基于数组的对象,而不是基于散列的对象。这是一个便宜(有效)的解决方案,因为它只会导致违规者与现有的类型检查发生冲突。

例如,以下生成的对象只是对实际对象的引用。只需在方法中使用$$self而不是$self

$ perl -e'
   sub new {
      my $class = shift;
      my $self = bless(\{}, $class);
      # $$self->{...} = ...;
      return $self;
   }
   my $o = __PACKAGE__->new();
   my $id = $o->{id};
'
Not a HASH reference at -e line 9.
于 2016-02-08T13:06:22.190 回答
3

做到这一点的一种方法是使用“由内而外的对象”,其中对象只是一个有福的简单标量,并且数据是单独存储的。例如,参见Class::STD

于 2016-02-08T13:09:48.847 回答