Text::CSV::Flatten - Perl extension for transforming hierarchical data (nested arrays/hashes) to comma-separated value (csv) output according to a compact, readable, user-specified pattern.
use Text::CSV::Flatten; Text::CSV::Flatten->new( '.<index>.*', data => [{ a => 1, b => 2 }, { a => 3, b => 4 }], )->csv();
This module transforms hierarchical data (nested arrays/hashes) to comma-separated value (csv) output according to a compact, readable, user-specified pattern.
For example, the pattern .<index>.* transforms a data structure of the form
.<index>.*
[{ a => 1, b => 2 }, { a => 3, b => 4 }]
to the CSV output
a,b,index 1,2,0 3,4,1
The pattern .*.* applied to the same data gives the output
.*.*
0_a,0_b,1_a,1_b 1,2,3,4
The pattern .*.<key> gives the output
.*.<key>
0,1,key 1,3,a 2,4,b
It is hoped that the pattern specification is sufficiently powerful for this module to replace a lot of simple boiler-plate data transformations.
The dot-separated components represent the following:
<name> represents that the keys at that position should be put in a column named name in the csv output. This column will be considered a primary key, and the values belonging to those keys become rows;
<name>
* represents that the keys at that position in the pattern should be interpreted as column names; their values should be the values for that column, all beloning to the same row;
*
{column_name} or {column_name_1,column_name_2,...} is similar to *, but instead of capturing all the keys at that level of the hierarchy, it only captures the named columns.
{column_name}
{column_name_1,column_name_2,...}
anything else represents a literal key name.
If your pattern does not contain * or {...}, you need to pass an additional column_name => parameter to the constructor to specify the name for the single column where the value will go.
{...}
column_name =>
For the purposes of this description, an array should be seen as a collection of index => value pairs.
It is possible to specify several dot-separated paths in a single pattern, separated by spaces. In that case, all the paths need to have the same primary key (that is, the same set of names in <...>). Rows will be formed by joining the columns resulting from the different paths.
<...>
Text::CSV
Timo Kluck, <tkluck@infty.nl>
Copyright (C) 2016 by Timo Kluck
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.22.1 or, at your option, any later version of Perl 5 you may have available.
To install Text::CSV::Flatten, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Text::CSV::Flatten
CPAN shell
perl -MCPAN -e shell install Text::CSV::Flatten
For more information on module installation, please visit the detailed CPAN module installation guide.