NAME
Data::Struct - Simple struct building
SYNOPSIS
# Define the struct and its accessors.
struct
Foo
=> [
qw(foo bar)
];
struct
Foo
=>
qw(foo bar)
;
# alternative
# Construct the struct.
my
$object
= struct
"Foo"
;
# empty struct
my
$object
= struct
Foo
=> {
bar
=> 1 };
my
$object
= struct
Foo
=> {
foo
=>
"yes"
,
bar
=> 1 };
# Use it.
"bar is "
.
$object
->bar .
"\n"
;
# 1
$object
->bar = 2;
"bar is now "
.
$object
->bar .
"\n"
;
# 2
DESCRIPTION
A struct is a data structure that can contain values (attributes). The values of the attributes can be set at creation time, and read and modified at run time. This module implements a very basic and easy to use struct builder.
Attributes can be anything that Perl can handle. There's no checking on types. If you need structs with type checking and inheritance and other fancy stuff, use one of the many CPAN modules that implement data structures using classes and objects. Data::Struct deals with data structures and not objects, so I placed this module under the Data:: hierarchy.
To use Data::Struct, just use it. This will export the struct() function that does all the work.
To define a structure, call struct() with the name of the structure and a list of accessors to be created:
struct(
"Foo"
,
"foo"
,
"bar"
);
which can be nicely written as:
struct
Foo
=>
qw( foo bar )
;
To prevent ambiguities, defining a struct requires struct() to be called in void context.
To create an empty structure:
my
$s
= struct
"Foo"
;
To create a structure with one or more pre-initialised attributes:
my
$s
= struct
Foo
=> {
foo
=> 3,
bar
=>
"Hi"
};
To prevent ambiguities, creating a struct requires struct() to be called in scalar context.
When the structure has been created, you can use accessor functions to set and get the attributes:
"bar is "
.
$s
->bar .
"\n"
;
# "Hi"
$s
->bar = 2;
"bar is now "
.
$s
->bar .
"\n"
;
# 2
PECULIARITIES
Redefining a structure adds new attributes but leaves existing attibutes untouched.
struct
"Foo"
=>
qw(bar)
;
my
$s
= struct
"Foo"
=> {
bar
=> 2 };
struct
Foo
=>
qw(blech)
;
$s
->blech = 4;
say
$s
->bar;
# prints 2
say
$s
->blech;
# prints 4
This may change in a future version.
SUPPORT
Bugs should be reported via the CPAN bug tracker at
http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Data::Struct
For other issues, contact the author.
AUTHOR
Johan Vromans <jv@cpan.org>.
SEE ALSO
Object::Tiny, Object::Tiny::Lvalue, Object::Tiny::RW, Class::Struct.
COPYRIGHT
Copyright 2011 Johan Vromans
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.