如果用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自带的文档。
Perl Class::Struct
最新推荐文章于 2020-02-01 18:04:19 发布