The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Data::Struct - Simple struct building


  use Data::Struct;             # exports 'struct'

  # 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.
  print "bar is " . $object->bar . "\n";       # 1
  $object->bar = 2;
  print "bar is now " . $object->bar . "\n";   # 2


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:

  print "bar is " . $s->bar . "\n";       # "Hi"
  $s->bar = 2;
  print "bar is now " . $s->bar . "\n";   # 2


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.


Bugs should be reported via the CPAN bug tracker at

For other issues, contact the author.


Johan Vromans <>.


Object::Tiny, Object::Tiny::Lvalue, Object::Tiny::RW, Class::Struct.


Copyright 2011 Johan Vromans

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.