好用的Perl包 Class::Ref

2017-08-05 08:02:27来源:CSDN作者:hemmingway人点击

分享

包的链接 https://metacpan.org/pod/Class::Ref

网页上介绍是 Class::Ref - Automatic OO wrapping of container references
就是将一个哈希、数组引用到一个 package 中来使用。

下面给出一个例子:

#!/usr/bin/perluse FindBin qw($RealBin);use lib "$RealBin/lib";use lib "$RealBin";use Class::Ref;# example 1### creat a hash$test = {         foo => {                 bar => 'Hello World!'                 }         };$obj = Class::Ref->new($test);print $obj->foo->bar . "/n";    # returns "Hello World!"$obj->baz({ blah => 123 });print $obj->baz->blah . "/n";    # returns 123#example 2$group1 = {         foo => {                 bar => 'group1 Hello World!'                 }         };$group2 = {         server => {                 ip => '192.168.32.1',                dc => 'eqdc10',                 }         };$list = { %{$group1}, %{$group2} };$obj = Class::Ref->new($list);print $obj->foo->bar . "/n";   print $obj->server->ip . "/n";   print $obj->{server}{dc} . "/n";   # example 3$obj = Class::Ref->new({ foo => [{ bar => 'Hello Again!' }] });print $obj->foo->[0]->bar . "/n";    # returns "Hello Again!"

运行结果如下所示:
运行结果

再列举一个使用的例子,我们要做一个 Foo.pm 的包,可以使用 Class::Ref 来制作这个类的属性值, 通过引用绑定外部的哈希或者数组,具体使用见下面的代码,给出了详细的代码。

package Foo;use Carp;use Class::Ref;use strict;use vars qw($VERSION $Debug);########################################################################## Configuration Section$VERSION = '3.426';#########################################################################sub new {    @_ >= 1 or croak 'usage: Foo->new ({options})';    my ($class, $ARGS) = (@_);    my $self = bless {}, $class;    my $obj = Class::Ref->new($ARGS);    $self->{REF} = $obj;    return ($self);}sub test {    my $self = shift;    #     print $self->{REF}->{'foo'}{'bar'} . "/n";    #     print $self->{REF}->foo->bar . "/n";} # Dump 1;

测试使用代码如下:

#!/usr/bin/perluse FindBin qw($RealBin);use lib "$RealBin/lib";use lib "$RealBin";use Foo;###$group1 = {         foo => {                 bar => 'group1 Hello World!'                 }         };$group2 = {         server => {                 ip => '192.168.32.1',                dc => 'eqdc10',                 }         };$obj = Foo->new( { %{$group1}, %{$group2} } );$obj->run;

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台