Perl Class::Struct
2010-12-18 02:02
204 查看
如果用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自带的文档。
以下为一简单示例:
--------------------------------------------------------------------
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自带的文档。
相关文章推荐
- 关于C_C++中struct与class的区别
- Swift中文教程---类与结构(Struct,Class)
- struct和class的区别
- C++中结构体与类的区别(struct与class的区别)
- C# Struct和Class的区别
- class和struct做类型定义时的区别
- class和struct的区别以及类的内存结构
- 关于结构体Struct和类Class的比较
- .NET技术:.NET中class和struct的区别
- Struct和Class的区别 转
- C++中结构体与类的区别(struct与class的区别)
- class和struct
- struct和class的区别
- When should you use a class vs a struct in C++?
- C#中class与struct的区别[转]
- C#中struct与class的区别
- C++中struct与class的比较
- c#中类与结构的区别 struct与class的区别
- Struct和Class的区别
- 如何把csharp里面的class/struct转换成byte array