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

NAME

Data::DPath::Flatten - Convert complex data structure into key/value pairs

SYNOPSIS

  use Data::DPath::Flatten qw/flatten/;
  
  # Data can be arrays or hashes.
  my $hash = flatten( \@record );
  my $hash = flatten( \%record );
  
  # Aliases add more human readable field names.
  my $hash = flatten( \@record );
  my $hash = flatten( \%record );

DESCRIPTION

Data::DPath::Flatten transforms an arbitrary data structure into a hash of key/value pairs.

Why? To store raw data in an SQL database. ETL::Pipeline::Input returns arbitrary data structures. For example, Excel files return an array but XML files a hash. Data::DPath::Flatten gives me a unique key for each field in the file, regardless of the Perl data structure.

Use Data::DPath::Flatten where you need key/value pairs from arbitrary data. The module traverses nested data structures of any depth and converts into a single dimension.

FUNCTIONS

flatten( $data )

flatten takes an arbitrary data structure and converts into a one level array reference. Essentially, it flattens out nested data structures.

flatten returns a hash reference. The keys are Data::DPath paths into the original record. The value is the raw data value from the file.

The parameter $data is required. It is a reference to the input data structure.

  # Recursively traverse arrays and hashes. 
  my $hash = flatten( \@fields );
  my $hash = flatten( \%record );
  
  # Scalars work, but it's kind of pointless. These come out the same.
  my $hash = flatten( $single );
  my $hash = flatten( \$single );

When flatten encounters a HASH or ARRAY reference, it recursively traverses the nested structure. Circular references are traversed only once, to avoid infinite loops.

SCALAR references are dereferenced and the value stored.

All other references and objects are stored as references.

SEE ALSO

Data::DPath

REPOSITORY

https://github.com/rbwohlfarth/Data-DPath-Flatten

AUTHOR

Robert Wohlfarth <rbwohlfarth@gmail.com>

COPYRIGHT AND LICENSE

Copyright (c) 2022 Robert Wohlfarth

This module is free software; you can redistribute it and/or modify it under the same terms as Perl 5.10.0. For details, see the full text of the license in the file LICENSE.

This program is distributed in the hope that it will be useful, but without any warranty; without even the implied