如果用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, h => '%', t => 'IO::File' }; 运行出错,可以自己尝试一下。 运用struct可以实现C中的链表,树结构,自己可以尝试一下。更详细的介绍可以参考perl自带的文档。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。