Data::P...::Object(3)
π NAME π
Data::Printer::Object β the underlying object for Data::Printer. (Yep, this is the Data::P...::Object(3) page from the User Contributed Perl Documentation, bestie. We folded the header in so it didn't have to be all formal at the top.)
β¨ SYNOPSIS β¨
Unless you're writing a plugin, or looking for some configuration property details, the documentation you want is probably on Data::Printer. Seriously! π«Ά
π¦ DESCRIPTION π¦
This module implements the underlying object used by Data::Printer to parse, format, and print Perl data structures.
It is passed to plugins so they can rely on contextual information from the caller, like colors, spacing, and other options. Plugins get to be nosy in the best way. π
π COMMON PROPERTIES / ATTRIBUTES π
πΈ Scalar Options πΈ
show_taintedβ When set, it will detect and let you know about any tainted data (default:1). Note that this is a no-op unless your script is in taint mode, meaning it's running with different real and effective user/group IDs, or with the-Tflag. Seeperlsecfor extra information.show_unicodeβ Whether to label data that has the unicode flag set (default:1).show_dualvarβ Perl can interpret strings as numbers and vice-versa, but that doesn't mean it always gets it right. When this option is set to"lax", Data::Printer will show both values if they differ. If set to"strict", it will always show both values, and when set to"off"it will never show the second value (default:lax).show_lvalueβ Lets you know whenever a value is an lvalue (default:1).string_maxβ The maximum number of characters to display in a string. If the string is bigger than that, Data::Printer will trim a part of the string (set bystring_preserve) and replace it with the message set onstring_overflow. Set"string_max"to0to show all characters (default:4096).string_overflowβ Message to display oncestring_maxis reached. Defaults to"(...skipping __SKIPPED__ chars...)".string_preserveβ When the string has more characters thanstring_max, this option defines which part of the string to preserve. Can be set to'begin','middle', or'end'(default:'begin').scalar_quotesβ Which quotation character to use when printing strings (default:").escape_charsβ Use this to escape certain characters from strings, which could be useful if your terminal is in a different encoding than the data being printed. Can be set to'nonascii','nonlatin1','all', or'none'(default:none).unicode_charnamesβ Whether to use the character's names when escaping unicode (e.g.SNOWMANinstead of\x{2603}) (default:0).print_escapesβ Whether to print invisible characters in strings, like\b,\n, and\t(default:0).resolve_scalar_refsβ If a reference to a scalar value is found more than once, print the resolved value. For example, you may have an object that you reuse to represent'true'or'false'. If you have more than one of those in your data, Data::Printer will by default print the second one as a circular reference. When this option is set to true, it will instead resolve the scalar value and keep going (default:false).
π Array Options π
array_maxβ The maximum number of array elements to show. If the array is bigger than that, Data::Printer will trim the offending slice (set byarray_preserve) and replace it with the message set onarray_overflow. Set"array_max"to0to show all elements in the array, regardless of array size (default:100).array_overflowβ Message to display oncearray_maxis reached. Defaults to"(...skipping __SKIPPED__ items...)".array_preserveβ When an array has more elements thanarray_max, this option defines which part of the array to preserve. Can be set to'begin','middle', or'end'(default:'begin').indexβ When set, shows the index number before each array element (default:1).
π Hash Options π
align_hashβ If this option is set, hash keys will be vertically aligned by the length of the longest key.
This is better explained with an example, so consider the hash my %h = ( a => 123, aaaaaa => 456 ). This would be an unaligned output:
a => 123,
aaaaaa => 456
and this is what it looks like with align_hash = 1:
a => 123,
aaaaaa => 456
(default: 1)
hash_maxβ The maximum number of hash key/value pairs to show. If the hash is bigger than that, Data::Printer will trim the offending slice (set byhash_preserve) and replace it with the message set onhash_overflow. Set"hash_max"to0to show all elements in the hash, regardless of the total keys (default:100).hash_overflowβ Message to display oncehash_maxis reached. Defaults to"(...skipping __SKIPPED__ keys...)".hash_preserveβ When a hash has more elements thanhash_max, this option defines which part of the hash to preserve. Can be set to'begin','middle', or'end'. Note that Perl makes no promises regarding key order, so this option only makes sense if keys are sorted. In other words, if you have disabledsort_keys, expect random keys to be shown regardless of which part was preserved (default:'begin').hash_separatorβ What to use to separate keys from values. Default is' '(three spaces).sort_keysβ Whether to sort keys when printing the contents of a hash (default:1).quote_keysβ Whether to quote hash keys or not. Can be set to1(always quote),0(never quote), or'auto'to quote only when a key contains spaces or linebreaks (default:'auto').
π§ Caller Information π§
Data::Printer can add an informational message to every call to p() or np() if you enable "caller_info". So for example if you write:
my $var = "meep!";
p $var, caller_info => 1;
this will output something like:
Printing in line 2 of myapp.pl:
"meep!"
The following options let you customize the message and how it is displayed.
caller_infoβ Set this option to a true value to display a message next to the data being printed (default:0).caller_messageβ What message to print whencaller_infois true.
Defaults to "Printing in line __LINE__ of __FILENAME__".
If the special strings "__LINE__", "__FILENAME__", or "__PACKAGE__" are present in the message, they'll be interpolated into their according value so you can customize the message at will:
caller_message = "[__PACKAGE__:__LINE__]"
caller_message_newlineβ When true, skips a line when printingcaller_message. When false, only a single space is added between the message and the data (default:1).caller_message_positionβ This option controls where thecaller_messagewill appear in relation to the code being printed. Can be set to'before'or'after'. A line is always skipped between the message and the data (either before or after), unless you setcaller_message_newlineto0(default:'before').
π₯ General Options π₯
arrowsβ Data::Printer shows circular references as a data path, indicating where in the data that reference points to. You may use this option to control if/when it should print reference arrows. Possible values are'all'(e.g."var->{x}->[y]->[z]"),'first'("var->{x}[y][z]"), or'none'("var{x}[y][z]"). Default is'none'.coloredβ Whether to colorize the output or not. Can be set to1(always colorize),0(never colorize), or'auto'. Default is'auto', meaning it will colorize only when printing toSTDOUTorSTDERR, never to a file or to a variable. The'auto'setting also respects the"ANSI_COLORS_DISABLED"environment variable.deparseβ If the data structure contains a subroutine reference (coderef), this option can be set to deparse it and print the underlying code, which hopefully resembles the original source code (default:0).coderef_stubβ If the data structure contains a subroutine reference (coderef) and the'deparse'option above is set to false, Data::Printer will print this instead (default:"sub { ... }").coderef_undefinedβ If the data structure contains a subroutine reference (coderef) that has not actually been defined at the time of inspection, Data::Printer will print this instead. Set it to'0'to disable this check, in which case Data::Printer will use whatever value you set oncoderef_stubabove (default:'<undefined coderef>').end_separatorβ When set, the last item on an array or hash will always contain a trailing separator (default:0).show_memsizeβ Set to true and Data::Printer will show the estimate memory size of the data structure being printed. RequiresDevel::Size(default:0).memsize_unitβ Ifshow_memsizeis on, this option lets you specify the unit in which to show the memory size. Can be set to"b"to show size in bytes,"k"for kilobytes,"m"for megabytes, or"auto", which will use the biggest unit that makes sense (default:auto).outputβ Where you want the output to be printed. Can be set to the following values:'stderr'β outputs to the standard error handle.'stdout'β outputs to the standard output handle.- reference to a scalar (e.g.
"\$string") β outputs to the scalar reference. - file handle β any open file handle:
open my $fh, '>>', '/path/to/some/file.log' or die $!;
p @{[ 1,2,3 ]}, output => $fh;
- file path β if you pass a non-empty string that is not
'stderr'nor'stdout', Data::Printer will consider it to be a file path and create/append to it automatically for you. So you can do this in your".dataprinter":
output = /path/to/some/file.log
By default, Data::Printer will print to the standard error (stderr).
max_depthβ This setting controls how far inside the data structure we should go (default:0for no depth limit).return_valueβ Whether the user wants the return value to be a pass-through of the source data ('pass'), the dump content itself ('dump'), or nothing at all ('void').
Defaults to 'pass' since version 0.36. NOTE: if you set it to 'dump', make sure it's not the last statement of a subroutine or that, if it is, the sub is only called in void context.
separatorβ The separator character(s) to use for arrays and hashes. The default is the comma",".show_readonlyβ When this option is set, Data::Printer will let you know whenever a value is read-only (default:1).show_refcountβ Whether to show data refcount when it's above1(default:0).show_weakβ When this option is set, Data::Printer will let you know whenever it finds a weak reference (default:1).show_tiedβ When set to true, this option will let you know whenever a tied variable is detected, including what is tied to it (default:1).themeβ the example value is:
theme = Monokai
theme π β this setting gets/sets the current color theme module. The default theme is Material. Data::Printer ships with several themes for you to choose from, and you can create your own theme or use any other from CPAN. aesthetic choices are valid choices β¨
warnings π«Ά β if something goes wrong when parsing your data or printing it to the selected output, Data::Printer by default shows you a warning from the standpoint of the actual call to p() or np(). Wanna silence those warnings? Just set this option to 0. peace and quiet, bestie π
π¦ Class / Object Options π¦
class_method β when Data::Printer is printing an object, it first looks for a method named "_data_printer" and, if one is found, we call it instead of actually parsing the structure.
The way this slays is that module authors get to control how Data::Printer outputs their objects, the best possible way, by literally just adding a private method instead of having to write a whole entire filter or even adding Data::Printer as a dependency. main character energy for module authors honestly π
To disable this behavior, simply set this option to false or an empty string. You can also change it to a different name and Data::Printer will look for that instead. π
class β class properties to override.
This "namespace" gets/sets all class properties that are used by the standard class filter that ships with Data::Printer. Note that, if you are using a specific filter for that object, most (if not all) of the settings below will not apply. iykyk π
In your .dataprinter file, the defaults would look like this:
class.parents = 1
class.linear_isa = auto
class.universal = 0
class.expand = 1
class.stringify = 1
class.show_reftype = 0
class.show_overloads = 1
class.show_methods = all
class.sort_methods = 1
class.inherited = public
class.format_inheritance = lines
class.parent_filters = 1
class.internals = 1
In code, you should use the class namespace as a key to a hash reference:
use Data::Printer class => {
parents => 1,
linear_isa => 'auto',
universal => 0,
expand => 1,
stringify => 1,
show_reftype => 0,
show_overloads => 1,
show_methods => 'all',
sort_methods => 1,
inherited => 'public',
format_inheritance => 'lines',
parent_filters => 1,
internals => 1,
};
Or inline:
p $some_object, class => { internals => 1, ... };
parents β when set, shows all superclasses of the object being printed. (default: 1) πΈ
linear_isa β this setting controls whether to show the linearized @ISA, which is the order of preference in which the object's methods and attributes are resolved according to its inheritance. Can be set to 1 (always show), 0 (never show) or 'auto', which shows only when the object has more than one superclass. (default: 'auto') π¦
universal β set this option to 1 to include UNIVERSAL methods to the list of public methods (like can and isa). (default: 0) β
expand β sets how many levels to descend when printing classes, in case their internals point to other classes. Set this to 0 to never expand any objects, just show their name. Set to any integer number and when Data::Printer reaches that depth, only the class name will be printed. Set to 'all' to always expand objects found inside your object. (default: 1) π₯
stringify β when this option is set, Data::Printer will check if the object being printed contains any methods named "as_string", "to_string" or "stringify". If it does, Data::Printer will use it as the object's output instead of the generic class plugin. (default: 1) π
show_reftype β if set to a true value, Data::Printer will show the internal reference type of the object. (default: 0) π
show_overloads β this option includes a list of all overloads implemented by the object. (default: 1) π
show_methods β controls which of the object's direct methods to show. Can be set to 'none', 'all', 'private' or 'public'. When applicable (Moo, Moose) it will also show attributes and roles. (default: 'all') π
sort_methods β when listing methods, attributes and roles, this option will order them alphabetically, rather than on whatever order the list of methods returned. (default: 1) β¨
inherited β controls which of the object's parent methods to show. Can be set to 'none', 'all', 'private' or 'public'. (default: 'public') π
format_inheritance β this option controls how to format the list of methods set by a parent class (and not the class itself). Setting it to 'lines' it will print one line for each parent, like so:
public methods (5):
foo, bar
Parent::Class:
baz, meep
Other::Parent:
moop
Setting it to 'string', it will put all methods on the same line:
public methods (5): foo, bar, baz (Parent::Class), meep (Parent::CLass), moop (Other::Parent)
Default is: 'lines'. (and yes, that Parent::CLass is exactly how it's written in the original, no cap π)
parent_filters β if there is no filter for the given object's class, there may still be a filter for one of its parent classes. When this option is set, Data::Printer will traverse the object's superclass and use the first filter it finds, if one is present. (default: 1) π§
internals β shows the object's internal data structure. (default: 1) π
π "Shortcuts" π
Some options are so often used together we have created shortcuts for them. bestie convenience features fr fr π«Ά
πΈ as
p $somevar, as => 'is this right?';
The "as" shortcut activates caller_info and sets caller_message to whatever you set it to. It's really useful to quickly differentiate between sequential uses of p(). obsessed with this one honestly
πΈ multiline
p $somevar, multiline => 0;
When set to 0, disables array index and linebreaks, uses ':' as hash separator and '(...)' as overflow for hashes, arrays and strings, and also disables 'caller_message_newline' so any caller message is shown on the same line as the variable being printed. If this is set on a global configuration or on the .dataprinter file, Can be "undone" by setting it to "1". π¦
πΈ fulldump
p $somevar, fulldump => 1;
By default, Data::Printer limits the size of string/array/hash dumps to a (hopefully) reasonable size. Still, sometimes you really need to see everything. To completely disable such limits, just set this option to true. gimme the whole dump, no crumbs ππ₯
π Methods and Accessors for Filter Writers π
The following attributes could be useful if you're writing your own custom filters or maybe even a non-obvious profile. Otherwise, no need to worry about any of them ;)
And make sure to check out the current filter list for real usage examples! β
π indent
π outdent
π newline
These methods are used to control the indentation level of the string being created to represent your data. While "indent" and "outdent" respectively increase and decrease the indentation level, "newline" will add a linebreak and position the "cursor" where you are expected to continue your dump string:
my $output = $ddp->newline . 'this is a new line';
$ddp->indent;
$output .= $ddp->newline . 'this is indented';
$ddp->outdent;
$output .= $ddp->newline . 'back to our previous indentation!';
Unless multiline was set to 0, the code above should print something like:
this is a new line
this is indented
back to our previous indentation
π¦ extra_config
Data::Printer will read and pass-through any unrecognized settings in either your .dataprinter file or your inline arguments inside this structure. This is useful to create custom settings for your filters. π«Ά
While any and all unknown settings will be readable here, we recommend you prepend them with a namespace like "filter_xxx" as those are reserved for filters and thus guaranteed not to colide with any core Data::Printer settings now or in the future. (yes, "colide" β we're keeping it π)
For example, on the Web filter we have the "expand_headers" option, and even though Data::Printer itself doesn't have this option, we prepend everything with the "filter_web" namespace, either in the config file:
filter_web.expand_headers = 1
or inline:
p $http_response, filters => ['Web'], filter_web => { expand_headers => 1 };
π maybe_colorize( $string, $label )
π maybe_colorize( $string, $label, $default_color )
my $output = $ddp->maybe_colorize( 12.3, 'number');
Instead of simply adding raw content to your dump string, you should wrap it with this method, as it will look up colors on the current theme and print them (or not, depending on whether the terminal supports color or the user has explicitly turned them off). π
If you are writing a custom filter and don't want to use the core labels to colorize your content, you may want to set your own label and pass a default color. For example:
my $output = $ddp->maybe_colorize( $data, 'filter_myclass', '#ffccb3' );
In the code above, if the user has "colors.filter_myclass" set either on the .dataprinter file or the runtime hashref, that one will be used. Otherwise, Data::Printer will use '#ffccb3'. custom palette era β¨
π current_depth
Shows the current depth level, from 0 onwards.
π current_name
Gets/sets the name for the current posistion, to be printed when the parser visits that data again. E.g. "var[0]{abc}[2]". (typo "posistion" is canon, we don't fix π
)
π parse( $data_ref )
π parse( $data_ref, %options )
This method receives a reference to a data structure to parse, and returns the parsed string. It will call each filter and colorize the output accordingly. π₯
Use this inside filters whenever you want to use the result of a parsed data strucure.
my $output = $ddp->parse( [3,2,1] );
An optional set of parameters may be passed:
"force_type => $type"β forces data to be treated as that type, where $type is the name of the Perl data strucuture as returned byScalar::Util::reftype(e.g.'HASH','ARRAY'etc). This is used when a filter wants to show the internals of blessed data. Otherwiseparsewould just call the same filter over and over again. π"seen_override => 1"β Data::Printer::Object tries to remember if it has already seen a data structure before, so it can show the circular reference instead of entenring an infinite loop. However, there are cases when you want to print the same data structure twice, like when you're doing a second pass on a blessed object to print its internals, or if you're using the same object over and over again. This setting overrides the internal counter and prints the same data again. Checkunseebelow for another way to achieve this. πΈ
π parse_as( $type, $data_ref )
This is a convenience method whose whole job is to force some data to be interpreted as a particular type. Itβs literally the same as this, no cap:
$ddp->parse( $data, force_type => $type, seen_override => 1 );
π«Ά unsee( $data ) π«Ά
Sometimes youβre writing a filter for data you <em>know</em> is gonna be repeated several times β think JSON Boolean objects, iykyk. To stop Data::Printer from showing that content as repeated, you can use the unsee method to make the current object forget about having ever visited this data. β¨
π OBJECT CONSTRUCTION π
Youβll most likely never need this unless youβre planning on extending Data::Printer itself. Like, this is deep-lore territory, bestie.
π new( %options ) π
Creates a new Data::Printer::Object instance. It may β optionally β receive a hash or a hash reference with custom settings for any of its properties. Constructor behavior, very main character energy. π
π SEE ALSO π
Data::Printer
Thatβs the whole page, bestie π«Ά β this one comes from perl v5.42.0 and is dated 2024-01-23, periodt. π
π¦ where this page comes from
- opensuse-leap 16.0: perl-Data-Printer 1.002001-bp160.1.11 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms