The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Datify - Simple stringification of data.

SYNOPSIS

 use Datify;

 my $datify = Datify->new( ... );   # See OPTIONS below
 $datify = $datify->set( ... );     # See OPTIONS below

 print $datify->varify( data => [...] ), "\n";  # "@data = (...);\n"

 # Or

 Datify->set( ... );                # See OPTIONS below
 print Datify->varify( data => [...] ), "\n";
 # "@data = (...);\n"

DESCRIPTION

Datify is very similar to Data::Dumper, except that it's easier to use, and has better formatting and options.

OPTIONS

Varify options

name => '$self'

The name of the default variable. This is also set as the first parameter to varify.

assign => '$var = $value;'

What an assignment statement should look like. If the generated code is to be run under use strict;, then you may want to change this to 'my $var = $value;'.

list => '($_)'

The delimiters for a list.

list_sep => ', '

The separator between list elements.

beautify => undef

Set this to a CODE reference that you would like to use to beautify the code. It should accept the code as the first parameter, process it, and return the code after all the beauty modifications have been completed.

An example:

 use Datify;
 use Perl::Tidy;

 sub beautify {
     my $source = shift;

     my ($dest, $stderr);
     Perl::Tidy::perltidy(
         argv => [ qw(
             --perl-best-practices
             --noprofile
             --nostandard-output
             --standard-error-output
             --nooutdent-long-lines
         ) ],
         source      => \$source,
         destination => \$dest,
         stderr      => \$stderr,
         errorfile   => \$stderr,
     ) && die $stderr;

     return $dest;
 }

 Datify->set( beautify => \&beautify );

 say Datify->varify( var => $var );

Undefify options

null => 'undef'

What to use as the null value.

Booleanify options

true => 1
false => "''"

What to use as the values for true and false, respectively. Since Perl does not have native boolean values, these are placeholders.

Stringify options

quote => undef

What to use as the default quote character. If set to a false value, then use the best guess. See "stringify( value )".

quote1 => "'"

The default single-quoting character.

quote2 => '"'

The default double-quoting character.

q1 => 'q'

The special single-quoting character starter.

q2 => 'qq'

The special double-quoting character starter.

sigils => '$@'

The characters in a double quoted sting that need to be quoted, or they may be interpreted as variable interpolation.

longstr => 1_000

How long a string needs to be before it's considered long. See "stringify( value )". Change to a false value to indicate no string is long. Change to a negative value to indicate every string is long.

encode1 => { ... }
92 => '\\\\'
byte => '\\%c'
encode2 => { ... }
0 => '\0'
7 => '\a'
8 => '\b'
9 => '\t'
10 => '\n'
12 => '\f'
13 => '\r'
27 => '\e'
92 => '\\\\'
also => '[:cntrl:]'
byte => '\x%02x'
wide => '\x{%04x}'

How to encode characters that need encoding.

number => 'encoding'

Encode the character with ordinal number as 'encoding'.

also => '[:cntrl:]'

Encode this range of characters, too.

byte => '\x%02x'

Encode characters that do not otherwise have an encoding with this sprintf expression.

byte2 => undef

Used to encode 2 byte UTF-8 sequences. If unset, then 2-byte sequences are encoded by using they byte encoding twice.

byte3 => undef

Used to encode 3 byte UTF-8 sequences. If unset, then 3-byte sequences are encoded by using they byte encoding three times.

byte4 => undef

Used to encode 4 byte UTF-8 sequences. If unset, then 4-byte sequences are encoded by using they byte encoding four times.

utf => undef

Use the internal encoding routines to encode characters. Set it to 8 to encode as UTF-8, or set it to 16 to encode as UTF-16.

vwide => undef

Encode very wide characters that do not otherwise have an encoding with this sprintf expression. If unset, then very wide characters are encoded with wide twice.

wide => '\x{%04x}'

Encode wide characters that do not otherwise have an encoding with this sprintf expression.

qpairs => [ qw\ () <> [] {} \ ]
qquotes => [ qw\ ! # % & * + , - . / : ; = ? ^ | ~ $ @ ` \ ]

When determining the quote character to use, go through these lists to see which character would work best.

Numify options

infinite => "'inf'"

What to use to indicate infinity.

-infinite => "'-inf'"

What to use to indicate negative infinity.

nonnumber => "'nan'"

What to use to indicate this is not a number.

num_sep => '_'

What character to use to seperate sets of numbers.

Scalarify options

scalar_ref => '\do{1;$_}'

How to generate a reference to a scalar.

LValueify options

lvalue => 'substr($lvalue, 0)'

How to generate a LValue.

VStringify options

vformat => 'v%vd'
vsep => undef

The formatting string to use. If vsep is set, then vformat should use the * format to inidicate what vsep will be: vformat => 'v%*vd', vsep => '.'.

Regexpify options

quote3 => '/'
q3 => 'qr'
encode3 => { ... }
0 => '\0'
7 => '\a'
9 => '\t'
10 => '\n'
12 => '\f'
13 => '\r'
27 => '\e'
also => '[:cntrl:]'
byte => '\x%02x'
wide => '\x{%04x}'

How to encode characters that need encoding. See "encode2 => { ... }"

Arrayify options

array_ref => '[$_]'

The representation of an array reference.

Hashify options

hash_ref => '{$_}'

The representation of a hash reference.

pair => '$key => $value'

The representation of a pair.

keyfilter => undef

A reference to an ARRAY, CODE, HASH, Regexp, or SCALAR, which will be converted to a the appropriate code, and used to filter the keys in a hash via grep.

ARRAY entries are changed into a HASH, with the entries set to be the inverse of keyfilterdefault.

CODE entires should look for the key name in $_, and return a boolean value.

HASH entries should have a true or false value, to indicate if the entry should be included.

Regexp entries are matched, and if true, then return the inverse of $keyfilterdefault.

SCALAR entries treat all values according to the boolean evaluation.

keyfilterdefault => 1

When filtering keys in a hash, if the key is not found in the keyfilter HASH or ARRAY, should it pass through or not?

keymap => undef

If you want to remap keys in a hash, assign a reference to some code that will be passed the object and the key, and should return the new key.

keysort => \&Datify::keysort

How to sort the keys in a hash. This has a performance hit, but it makes the output much more readable. See the description of "keysort($$)".

keywords => [qw(undef)]

Any keywords that should be quoted, even though they may not need to be.

Objectify options

overloads => [ '""', '0+' ]

The list of overloads to check for before deconstructing the object. See overload for more information on overloading.

object => 'bless($data, $class_str)'

The representation of an object. Other possibilities include '$class($data)' or '$class->new($data)'.

IOify options

io => '*$name{IO}'

The representation of unknown IO objects.

Codeify options

code => 'sub {$_}'

The representation of a code reference. This module does not currently support decompiling code to make a complete representation, but if passed a representation, can wrap it in this.

codename => '\&$_'

The representation of a code reference by name.

body => '...'

The representation of the body to a code reference. This module does not currently support decompiling code to make a complete representation.

Refify options

reference => '\\$_'

The representation of a reference.

dereference => '$referent->$place'

The representation of dereferencing.

nested => '$referent$place'

The representation of dereferencing a nested reference.

Formatify options

format => "format UNKNOWN =\n.\n"

The representation of a format. This module does not currently support showing the acutal representation.

METHODS

new( name => value, name => value, ... )

Create a Datify object with the following options.

See "OPTIONS" for a description of the options and their default values.

exists( name, name, ... )

Determine if values exists for one or more settings.

Can be called as a class method or an object method.

get( name, name, ... )

Get one or more existing values for one or more settings. If passed no names, returns all parameters and values.

Can be called as a class method or an object method.

set( name => value, name => value, ... )

Change the "OPTIONS" settings. When called as a class method, changes default options. When called as an object method, changes the settings and returns a new object.

See "OPTIONS" for a description of the options and their default values.

NOTE: When called as a object method, this returns a new instance with the values set, so you will need to capture the return if you'd like to persist the change:

 $datify = $datify->set( ... );

add_handler( $class => \&code_ref )

Add a handler to handle an object of type $class. \&code_ref should take two parameters, a reference to Datify, and the object to be Datify'ed. It should return a representation of the object.

If $class is unspecified, assumes that it's handling for the package where add_handler is called from.

 # Set URI's to stringify as "URI->new('http://example.com')"
 # instead of "bless(\'http://example.com', 'URI')"
 Datify->add_handler( 'URI' => sub {
     my ( $datify, $uri ) = @_;
     my $s = $datify->stringify("$uri");
     return "URI->new($s)";
 } );

varify( name => value, value, ... )

Returns an assignment statement for the values. If name does not begin with a sigil ($, @, or %), will determine which sigil to use based on values.

Some examples:

Common case, determine the type and add the correct sigil to 'foo'.

 Datify->varify(   foo  => $foo );

Specify the type.

 Datify->varify( '$foo' => $foo );

Handle a list: @foo = (1, 2, 3);

 Datify->varify( '@foo' =>   1, 2, 3   );
 Datify->varify( '@foo' => [ 1, 2, 3 ] );
 Datify->varify(   foo  =>   1, 2, 3   );
 Datify->varify(   foo  => [ 1, 2, 3 ] );

Handle a hash: %foo = (a => 1, b => 2, c => 3); (Note: Order may be rearranged.)

 Datify->varify( '%foo' =>   a => 1, b => 2, c => 3   );
 Datify->varify( '%foo' => { a => 1, b => 2, c => 3 } );
 Datify->varify(   foo  => { a => 1, b => 2, c => 3 } );

Keep in mind that without proper hints, this would be interpretted as a list, not a hash:

 Datify->varify(   foo  =>   a => 1, b => 2, c => 3   );
 # "@foo = ('a', 1, 'b', 2, 'c', 3);"

undefify

Returns the string that should be used for an undef value.

booleanify( value )

Returns the string that represents the true or false interpretation of value. Will return the value for undefify if value is not defined.

stringify1( value , delimiters )

Returns the string that represents value as a single-quoted string. The delimiters parameter is optional.

stringify2( value , delimiters )

Returns the string that represents value as a double-quoted string. The delimiters parameter is optional.

stringify( value )

Returns the string the represents value. It will be a double-quoted string if it is longer than the longstr option or contains control characters. It will be a single-quoted string unless there are single-quotes within the string, then it will be a double-quoted string, unless it also contains double-quotes within the string, then it will attempt to find the best quote character.

is_numeric( value )

Returns true if value is can be numeric, returns false if the value is not numeric (including inf and nan), returns undef if the value is undefined.

 Datify->is_numeric(1234.5678901);       #          true
 Datify->is_numeric("inf");              #          false
 Datify->is_numeric( "inf" / "inf" );    # "nan" => false
 Datify->is_numeric(undef);              #          undef

numify( value )

Returns value with seperators between the hundreds and thousands, hundred-thousands and millions, etc. Similarly for the fractional parts.

 Datify->numify(1234.5678901);    # "1_234.56_789_01"

Also returns the string that should be used for the infinite, -infinite, and nonnumber values, the null value for undefined values, and nonnumber value for all not-a-numbers.

 Datify->numify('inf');              # 'inf'
 Datify->numify( 'inf' / 'inf' );    # 'nan'
 Datify->numify(undef);              # 'undef'
 Datify->numify('apple');            # 'nan'

scalarify( value )

Returns value as a scalar. If value is not a reference, performs some magic to correctly print vstrings and numbers, otherwise assumes it's a string. If value is a reference, hands off to the correct function to create the string.

Handles reference loops.

lvalueify( value )

Returns an approximate representation of what the lvalue is.

vstringify( value )

A representation of the VString, in dotted notation.

regexpify( value, delimiters )

A representation of the Regexp in value.

listify( value, value, ... )

Returns value(s) as a list.

 Datify->listify( 1, 2, 3 );    # '1, 2, 3'

arrayify( value, value, ... )

Returns value(s) as an array.

 Datify->arrayify( 1, 2, 3 );    # '[1, 2, 3]'

is_keyword( word )

Checks if word has been set in the "keywords => [qw(undef)]" list.

keyify( value )

Returns value as a key. If value does not need to be quoted, it will not be. Verifies that value is not a keyword.

hashkeys( $hash )

Returns the keys of a hash, filtered (see "keyfilter => undef"), and sorted (see "keysort").

pairify( value => value, ... )

Returns value(s) as a pair.

 Datify->pairify( a => 1, b => 2 );    # 'a => 1, b => 2'

hashify( value, value, ... )

Returns value(s) as a hash.

 Datify->hashify( a => 1, b => 2 );    # '{a => 1, b => 2}'

overloaded( $object )

Returns the first method from the overloads list that $object has overloaded. If nothing is overloaded, then return nothing.

objectify( value )

Returns value as an object. Tries several different ways to find the best representation of the object.

If a handler has been defined for the object with "add_handler( $class => \&code_ref )", then use that. If the object has overloaded any of "overloads => [ '""', '0+' ]", then use that to represent the $data portion of the object. If the object has an _attrkeyvals method, then that will be used to gather the elements of the object. If the object has none of those things, then the object is inspected and handled appropriately.

 Datify->objectify($object);    # "bless({}, 'Object')"

ioify( value )

Returns a representation of value that is accurate if value is STDIN, STDOUT, or STDERR. Otherwise, returns the io setting.

codeify( value )

Returns a representation of a reference to a subroutine. If value is not a reference, then uses that as the body of the anonymous subroutine. If value is a CODE reference, does some introspection on it, and expresses as a reference to the named subroutine, or to a generic anonymous function. If value is another type of reference, then expressed as an anonymous function returning that. Otherwise, returns a generic anonymous function.

 Datify->codeify( 'return $_' );               # 'sub { return $_ }'
 Datify->codeify( \&MyModule::subroutine );    # '\&MyModule::subroutine'
 Datify->codeify( sub {"!"} );                 # 'sub { ... }'
 Datify->codeify( [1, 2, 3] );                 # 'sub { [1, 2, 3] }'

refify( value )

Returns value as reference.

formatify( value )

Returns a value that is not completely unlike value.

globify( value )

Returns a representation of value. For normal values, remove the leading main::.

beautify( ify => values )

Calls "beautify" on the output of the *ify method with values.

If there has been no beautify method specified, returns the raw output from the *ify method.

    say( Datify->beauitfy( scalarify => $scalar ) );

FUNCTIONS

keysort($$)

Not a method, but a sorting routine that sorts numbers (using <=>) before strings (using cmp).

BUGS

Please report any bugs or feature requests on the bugtracker website https://github.com/rkleemann/Datify/issues

When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.

TODO

  • Handle formats better.

SEE ALSO

Data::Dumper

VERSION

This document describes version v0.20.064 of this module.

AUTHOR

Bob Kleemann <bobk@cpan.org>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2014-2020 by Bob Kleemann.

This is free software, licensed under:

  The Artistic License 2.0 (GPL Compatible)