NAME

Data::Dumper::Interp - Data::Dumper optimized for humans, with interpolation

SYNOPSIS

use open IO => ':locale';
use Data::Dumper::Interp;

@ARGV = ('-i', '/file/path');
my %hash = (abc => [1,2,3,4,5], def => undef);
my $ref = \%hash;

# Interpolate variables in strings, substituting Data::Dumper output
say ivis 'FYI ref is $ref\nThat hash is: %hash\nArgs are @ARGV';

  -->FYI ref is {abc => [1,2,3,4,5], def => undef}
     That hash is: (abc => [1,2,3,4,5], def => undef)
     Args are ("-i","/file/path")

# Label interpolated values with "expr=" 
say dvis '@ARGV'; -->@ARGV=("-i","/file/path")

# Functions to format one thing 
say vis \@ARGV;   #any scalar   -->["-i", "/file/path"]
say avis @ARGV;   -->("-i", "/file/path")
say hvis %hash;   -->(abc => [1,2,3,4,5], def => undef)

# Stringify objects
{ use bigint;
  my $struct = { debt => 999_999_999_999_999_999.02 };
  say vis $struct;
    --> {debt => (Math::BigFloat)999999999999999999.02}
}

# Wide characters are readable
use utf8;
my $h = {msg => "My language is not ASCII ☻ ☺ 😊 \N{U+2757}!"};
say dvis '$h' ;
  --> h={msg => "My language is not ASCII ☻ ☺ 😊 ❗"}

#-------- OO API --------

say Data::Dumper::Interp->new()
    ->MaxStringwidth(50)->Maxdepth($levels)->vis($datum);

#-------- UTILITY FUNCTIONS --------
say u($might_be_undef);  # $_[0] // "undef"
say qsh($string);        # quote if needed for /bin/sh
say qshpath($pathname);  # quote except for ~ or ~username prefix

  system "ls -ld ".join(" ",map{ qshpath } ("/tmp", "~", "~sally/subdir"));

DESCRIPTION

The namesake feature of this module is interpolating Data::Dumper output into strings. In addition, simple functions are provided to visualize a scalar, array, or hash. And finally a few utilities to quote strings for /bin/sh.

Data::Dumper is used internally to visualize (i.e. format) data, with pre- and postprocessing to "improve" the results: Output is compact (1 line if possibe) and omits a trailing newline; Unicode characters appear as themselves, objects like Math:BigInt are stringified, and some Data::Dumper bugs^H^H^H^Hquirks are circumvented. See "DIFFERENCES FROM Data::Dumper".

FUNCTIONS

ivis 'string to be interpolated'

Returns the argument with variable references and escapes interpolated as in in Perl double-quotish strings, using Data::Dumper to format variable values.

$var is replaced by its value, @var is replaced by "(comma, sparated, list)", and %hash by "(key => value, ...)" visualizations.

Most Perl expressions are recognized including slices and method calls. For example

say ivis 'The value is ${\@myarray}[42]->{$key}->method(...)'

would print "The value is " followed by the Data:Dumper visualization of the value of that expression.

Expressions are evaluated in the caller's context using Perl's debugger hooks, and may refer to almost any lexical or global visible at the point of call (see "LIMITATIONS").

IMPORTANT: The argument string must be single-quoted to prevent Perl from interpolating it beforehand.

dvis 'string to be interpolated'

Like ivis with the addition that interpolated expressions are prefixed with a "exprtext=" label.

The 'd' in 'dvis' stands for debugging messages, a frequent use case where brevity of typing is more highly prized than beautiful output.

vis

vis SCALAR

avis LIST

hvis EVENLIST

These are the underlying functions used by ivis to visualize expressions.

vis formats a single scalar ($_ if no argument is given).

avis formats an array (or any list) as comma-separated values in parenthesis.

hvis formats a hash as key => value pairs in parens.

alvis LIST

hlvis EVENLIST

These variants produce a bare list without the enclosing parenthesis

ivisq 'string to be interpolated'

dvisq 'string to be interpolated'

visq [SCALAREXPR]

avisq LIST

hvisq LIST

alvisq LIST

hlvisq EVENLIST

Alternatives with a 'q' suffix display strings in 'single quoted' form if possible.

Internally, Data::Dumper is called with Useqq(0), but depending on the version of Data::Dumper the result may be "double quoted" anyway if wide characters are present.

OBJECT-ORIENTED INTERFACES

Data::Dumper::Interp->new()

Creates an object initialized from the global configuration variables listed below.

The functions described above may also be used as methods when called on a Data::Dumper::Interp object (when not called as a method they create a new object internally).

For example:

$msg = Data::Dumper::Interp->new()->Foldwidth(40)->avis(@ARGV);

returns the same string as

local $Data::Dumper::Interp::Foldwidth = 40;
$msg = avis(@ARGV);

Configuration Variables / Methods

These work in the same way as similar variables/methods in Data::Dumper.

Global variables determine the initial state of objects created by new, and the state of an object can be quieried or changed with corresponding methods. When a method is called with arguments to set a value, the method returns the object itself to facilitate chained calls.

The following configuration methods may be used:

$Data::Dumper::Interp::MaxStringwidth or $obj->MaxStringwidth(INTEGER)

$Data::Dumper::Interp::Truncsuffix or $obj->Truncsuffix("...")

Longer strings are truncated and Truncsuffix appended. MaxStringwidth=0 (the default) means no limit.

$Data::Dumper::Interp::Foldwidth or $obj->Foldwidth(INTEGER)

Defaults to the terminal width at the time of first use.

$Data::Dumper::Interp::Stringify or $obj->Stringify(BOOL);

or (classname);

or ([list of classnames]);

A false value disables object stringification.

A "1" (the default) enables stringification of all objects which support it (i.e. they overload the "" operator).

Otherwise stringification is enabled only for the specified class name(s).

$Data::Dumper::Interp::Sortkeys or $obj->Sortkeys(subref)

Controls sorting and optionally filtering of hash keys. See Data::Dumper documentation.

Data::Dumper::Interp provides a default which sorts numeric substrings in keys by numerical value (see "DIFFERENCES FROM Data::Dumper").

$Data::Dumper::Interp::Quotekeys or $obj->Quotekeys(subref)

See Data::Dumper documentation.

UTILITY FUNCTIONS

u

u SCALAR

Returns the argument ($_ by default) if it is defined, otherwise the string "undef".

qsh

qsh $string

qshpath

qshpath $might_have_tilde_prefix

The string ($_ by default) is quoted if necessary for parsing by /bin/sh, which has different quoting rules than Perl. "Double quotes" are used when no escapes would be needed, otherwise 'single quotes'.

If the string contains only "shell-safe" ASCII characters it is returned as-is, without quotes.

qshpath is like qsh except that an initial ~ or ~username is left unquoted. Useful for paths given to bash or csh.

If the argument is a ref it is first formatted as with vis() and the resulting string quoted. Undefined values appear as undef without quotes.

LIMITATIONS

Interpolated Strings

ivis and dvis evaluate expressions in the user's context using Perl's debugger support ('eval' in package DB -- see perlfunc). This mechanism has some limitations:

@_ will appear to have the original arguments to a sub even if "shift" has been executed. However if @_ is entirely replaced, the correct values will be displayed.

A lexical ("my") sub creates a closure, and variables in visible scopes which are not actually referenced by your code may not exist in the closure; an attempt to display them with ivis will fail. For example:

our $global;
sub outerfunc {
  my sub inner {
    say dvis '$global'; # croaks with "Error interpolating '$global'"
    # my $x = $global;  # ... unless this is un-commented
  }
  &inner();
}
&outerfunc;
Multiply-referenced items

If a structure contains several refs to the same item, the first ref will be visualized by showing the referenced item as you might expect.

However subsequent refs will look like $VAR1->place where place is the location of the first ref in the overall structure. This is how Data::Dumper indicates that the ref is a copy of the first ref and thus points to the same datum. "$VAR1" is an artifact of how Data::Dumper would generate code using its "Purity" feature. Data::Dumper::Interp does nothing special and simply passes through these annotations.

The special "_" stat filehandle may not be preserved

Data::Dumper::Interp queries the operating system to obtain the window size to initialize $Foldwidth, if it is not already defined; this may change the "_" filehandle. After the first call (or if you pre-set $Foldwidth), the "_" filehandle will not change across calls.

DIFFERENCES FROM Data::Dumper

Visualized data structures differ from using Data::Dumper directly as follows:

  • Everything is shown on a single line if possible, otherwise wrapped to the terminal width with indentation appropriate to structure levels.

    A final newline is not included.

  • Printable Unicode characters appear as themselves instead of \x{ABCD}.

    Note: If your data contains 'wide characters', you must encode the result before displaying it as explained in perluniintro. For example with use open IO = ':locale';>

    Undecoded binary octets (e.g. data read from a 'binmode' file) will be escaped as individual bytes when necessary.

  • Object refs are replaced by the object's stringified representation. For example, bignum and bigrat numbers are shown as easily readable values rather than "bless( {...}, 'Math::BigInt')".

    Stingified objects are prefixed with "(classname)" to make clear what happened.

  • Hash keys are sorted treating numeric "components" numerically. For example "A.20" sorts before "A.100".

  • Punctuation variables, including $@ and $?, are preserved over calls.

  • Representation of numbers and strings are made predictable and obvious: Floating-point values always appear as numbers (not 'quoted strings'), and strings containing digits like "42" appear as quoted strings and not numbers (string vs. number detection is ala JSON::PP).

    Such differences might not matter to Perl when executing code, but may be important when communicating to a human.

SEE ALSO

Data::Dumper

AUTHOR

Jim Avera (jim.avera AT gmail dot com)