NAME
Data::DefGen - Define and Generate arbitrary data.
SYNOPSIS
use Data::DefGen;
my $defn = def {
my $date = localtime;
return {
when => $date,
result => def { [ 1 .. rand(5), def { scalar reverse 'olleh' } ] },
topic => def { pick_one('foo', 'bar', 'baz') },
};
};
my $data = $defn->gen;
# Example of generated data
# {
# when => 'Sun Apr 19 12:48:16 2015',
# result => [1, 2, 3, 'hello'],
# topic => 'bar',
# }
# Generate 10 of these
my @datas = def { ($defn) x 10 }->gen;
DESCRIPTION
This module exports a single def
function that takes a CODE block to define a data structure. The returned structure may contain more definitions within it.
Calling gen
method on the returned object will recursively execute all the definitions, and return the entire generated data structure. Params passed to gen
will be received by all CODE definitions.
By default, a shallow copy is performed whenever a blessed object is encountered. To override this behavior, pass an obj_cloner
function, per def
block:
my $defn = def { ... } obj_cloner => sub { my_cloning($_[0]) };
Unlike gen
params, the obj_cloner
function does not propagate to nested definitions.
CREDIT
This was inspired by the JSON Generator http://www.json-generator.com/.
DEPENDENCIES
No non-core modules are required.
AUTHOR
Gerald Lai <glai at cpan dot org>