Perl Class::Struct

如果用perl来实现C的数据结构struct,请使用模块Class::Struct.

以下为一简单示例:
--------------------------------------------------------------------
use Data::Dumper;
use Class::Struct;
use IO::File;

struct Test =>{
    s => '$',         #定义使用scalar类型
    a => '@',         #定义使用array类型
    h => '%',         #定义使用hash类型
    t => 'IO::File'   #定义使用其它类
};

#struct 也可以用[]来定义,效果一样

$f = IO::File->new("<d:/tmp/test.pl");
$t = Test->new(
    s=>'this is just a testing',
    a=>[1,2,3],
    h=>{one=>'two',three=>4},
    t=>$f
    #这里也可以这样初始化 t=>(IO::File->new("<d:/tmp/test.pl"))
);

print $t->t->getline;
$x = $t->a;
push @$x,'testing';
print  Dumper $t

输出结果:
--------------------------------------------------------------------
$VAR1 = bless( {
                 'Test::t' => bless( /*Symbol::GEN1, 'IO::File' ),
                 'Test::s' => 'this is just a testing',
                 'Test::a' => [
                                1,
                                2,
                                3,
                                'testing'
                              ],
                 'Test::h' => {
                                'three' => 4,
                                'one' => 'two'
                              }
               }, 'Test' );


上例中如果不对每个域赋值,则结果会为:
$t = Test->new;
print Dumper $t

输出:
$VAR1 = bless( {
                 'Test::s' => undef,
                 'Test::a' => [],
                 'Test::h' => {}
               }, 'Test' );


struct无法定义默认初始值,可以尝试如下定义:
struct Test =>{
    s  => 'testing',
    a => [1,2,3],
    h => '%',
    t => 'IO::File'
};

运行出错,可以自己尝试一下。

运用struct可以实现C中的链表,树结构,自己可以尝试一下。更详细的介绍可以参考perl自带的文档。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值