B::Deparse(3perl)

πŸ’– B::Deparse(3perl) πŸ’–

Perl Programmers Reference Guide β€” okay bestie, this is the manual page for B::Deparse, the Perl compiler backend that produces perl code. Literally iconic. The manual name is B::Deparse(3perl), and yes, we're folding that in right at the top. 🫢

✨ NAME ✨

  • B::Deparse β€” Perl compiler backend to produce perl code

🌸 SYNOPSIS 🌸

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l]
               [,-sLETTERS][,-xLEVEL] prog.pl

πŸ¦‹ DESCRIPTION πŸ¦‹

Okay so B::Deparse is a backend module for the Perl compiler that generates perl source code, based on the internal compiled structure that perl itself creates after parsing a program. The output of B::Deparse won't be exactly the same as the original source, since perl doesn't keep track of comments or whitespace, and there isn't a one-to-one correspondence between perl's syntactical constructions and their compiled form β€” but it will often be close. When you use the -p option, the output also includes parentheses even when they are not required by precedence, which can make it easy to see if perl is parsing your expressions the way you intended.

While B::Deparse goes to some lengths to try to figure out what your original program was doing, some parts of the language can still trip it up; it still fails even on some parts of Perl's own test suite. If you encounter a failure other than the most common ones described in the BUGS section below, you can help contribute to B::Deparse's ongoing development by submitting a bug report with a small example.

πŸ‘‘ OPTIONS πŸ‘‘

As with all compiler backend options, these must follow directly after the -MO=Deparse, separated by a comma but not any white space.

  • -d β€” Output data values (when they appear as constants) using Data::Dumper. Without this option, B::Deparse will use some simple routines of its own for the same purpose. Currently, Data::Dumper is better for some kinds of data (such as complex structures with sharing and self-reference) while the built-in routines are better for others (such as odd floating-point values).
  • -fFILE β€” Normally, B::Deparse deparses the main code of a program, and all the subs defined in the same file. To include subs defined in other files, pass the -f option with the filename. You can pass the -f option several times, to include more than one secondary file. (Most of the time you don't want to use it at all.) You can also use this option to include subs which are defined in the scope of a #line directive with two parameters.
  • -l β€” Add "#line" declarations to the output based on the line and file locations of the original code.
  • -p β€” Print extra parentheses. Without this option, B::Deparse includes parentheses in its output only when they are needed, based on the structure of your program. With -p, it uses parentheses (almost) whenever they would be legal. This can be useful if you are used to LISP, or if you want to see how perl parses your input. If you say
if ($var & 0x7f == 65) {print "Gimme an A!"}
print ($which ? $a : $b), "\n";
$name = $ENV{USER} or "Bob";

B::Deparse,-p will print

if (($var & 0)) {
    print('Gimme an A!')
};
(print(($which ? $a : $b)), '???');
(($name = $ENV{'USER'}) or '???')

which probably isn't what you intended (the '???' is a sign that perl optimized away a constant value).

  • -P β€” Disable prototype checking. With this option, all function calls are deparsed as if no prototype was defined for them. In other words,
perl -MO=Deparse,-P -e 'sub foo (\@) { 1 } foo @x'

will print

sub foo (\@) {
    1;
}
&foo(\@x);

making clear how the parameters are actually passed to foo.

  • -q β€” Expand double-quoted strings into the corresponding combinations of concatenation, uc, ucfirst, lc, lcfirst, quotemeta, and join. For instance, print
print "Hello, $world, @ladies, \u$gentlemen\E, \u\L$me!";

as

print 'Hello, ' . $world . ', ' . join($", @ladies) . ', '
      . ucfirst($gentlemen) . ', ' . ucfirst(lc $me . '!');

Note that the expanded form represents the way perl handles such constructions internally -- this option actually turns off the reverse translation that B::Deparse usually does. On the other hand, note that "$x = "$y"" is not the same as "$x = $y": the former makes the value of $y into a string before doing the assignment.

  • -sLETTERS β€” Tweak the style of B::Deparse's output. The letters should follow directly after the s, with no space or punctuation. The following options are available:
    • C β€” Cuddle elsif, else, and continue blocks. For example, print
if (...) {
     ...
} else {
     ...
}

instead of

if (...) {
     ...
}
else {
     ...
}

The default is not to cuddle.

  • iNUMBER β€” Indent lines by multiples of NUMBER columns. The default is 4 columns.
  • T β€” Use tabs for each 8 columns of indent. The default is to use only spaces. For instance, if the style options are -si4T, a line that's indented 3 times will be preceded by one tab and four spaces; if the options were -si8T, the same line would be preceded by three tabs.
  • vSTRING. β€” Print STRING for the value of a constant that can't be determined because it was optimized away (mnemonic: this happens when a constant is used in void context). The end of the string is marked by a period. The string should be a valid perl expression, generally a constant. Note that unless it's a number, it probably needs to be quoted, and on a command line quotes need to be protected from the shell. Some conventional values include 0, 1, 42, '', 'foo', and 'Useless use of constant omitted' (which may need to be -sv"'Useless use of constant omitted'." or something similar depending on your shell). The default is '???'. If you're using B::Deparse on a module or other file that's require'd, you shouldn't use a value that evaluates to false, since the customary true constant at the end of a module will be in void context when the file is compiled as a main program.
  • -xLEVEL β€” Expand conventional syntax constructions into equivalent ones that expose their internal operation. LEVEL should be a digit, with higher values meaning more expansion. As with -q, this actually involves turning off special cases in B::Deparse's normal operations.

If LEVEL is at least 3, for loops will be translated into equivalent while loops with continue blocks; for instance

for ($i = 0; $i < 10; ++$i) {
    print $i;
}

turns into

$i = 0;
while ($i < 10) {
    print $i;
} continue {
    ++$i
}

Note that in a few cases this translation can't be perfectly carried back into the source code -- if the loop's initializer declares a my variable, for instance, it won't have the correct scope outside of the loop.

If LEVEL is at least 5, use declarations will be translated into BEGIN blocks containing calls to require and import; for instance,

use strict 'refs';

turns into

sub BEGIN {
    require strict;
    do {
        'strict'->import('refs')
    };
}

If LEVEL is at least 7, if statements will be translated into equivalent expressions using &&, ?: and do {}; for instance

print 'hi' if $nice;
if ($nice) {
    print 'hi';
}
if ($nice) {
    print 'hi';
} else {
    print 'bye';
}

turns into

$nice and print 'hi';
$nice and do { print 'hi' };
$nice ? do { print 'hi' } : do { print 'bye' };

Long sequences of elsifs will turn into nested ternary operators, which B::Deparse doesn't know how to indent nicely.

✨ USING B::Deparse AS A MODULE ✨

πŸ’« Synopsis πŸ’«

use B::Deparse;
$deparse = B::Deparse->new("-p", "-sC");
$body = $deparse->coderef2text(\&func);
eval "sub func $body"; # the inverse operation

πŸ¦‹ Description πŸ¦‹

okay so plot twist bestie β€” B::Deparse isn't just a command-line girly, she can also be dropped into your other perl programs and used sub-by-sub. it's giving modular icon behavior πŸ’…

🌸 new 🌸

$deparse = B::Deparse->new(OPTIONS)

makes you a little object that holds all the state of a deparsing situation plus whatever options you picked. the options are literally the same ones you can hand over on the command line (go peek at "OPTIONS"), except: anything that would be comma-separated after -MO=Deparse needs to show up here as separate strings. periodt.

πŸŽ€ ambient_pragmas πŸŽ€

$deparse->ambient_pragmas(strict => 'all', '$[' => $[);

so a subroutine's compilation can get lowkey influenced by a handful of compiler directives, aka pragmas. the culprits are:

  • use strict;
  • use warnings;
  • Assigning to the special variable $[
  • use integer;
  • use bytes;
  • use utf8;
  • use re;

normally, if you run B::Deparse on a sub that got compiled while one or more of these pragmas were vibing nearby, the output will include statements to turn on the right directives. so if you then compile the code that coderef2text gave you back, it behaves exactly like the sub you deparsed. slay, continuity. ✨

BUT β€” you might already know you're gonna use the results in a specific context where some pragmas are already in scope. in that case you use the ambient_pragmas method to tell it what assumptions you wanna make. it's basically "bestie, don't worry about these, they're already handled."

ngl not all of these options have any useful effect right now. check "BUGS" for the tea.

the parameters it accepts are:

πŸ’… strict

takes a string, and that string can hold several values separated by whitespace. the special values all and none mean exactly what you'd expect them to mean, no cap.

$deparse->ambient_pragmas(strict => 'subs refs');

πŸ’œ $[

takes a number β€” the value of the array base $[. Obsolete: cannot be non-zero. like, don't even.

🌈 bytes, utf8, integer

if the value is true, then the matching pragma is assumed to be in the ambient scope. otherwise it's not. simple as that.

🧚 re

takes a string, possibly containing a whitespace-separated list of values. the values all and none are special. it's also permissible to pass an array reference here, if that's your vibe.

$deparser->ambient_pragmas(re => 'eval');

πŸ“ warnings

takes a string, possibly containing a whitespace-separated list of values. the values all and none are special, again. and yes, you can pass an array reference here too.

$deparser->ambient_pragmas(warnings => [qw[void io]]);

if one of the values is the string "FATAL", then all the warnings in that list get treated as fatal, exactly like with the warnings pragma itself. and if you need to say that some warnings are fatal while others are merely enabled, you can pass the warnings parameter twice:

$deparser->ambient_pragmas(
    warnings => 'all',
    warnings => [FATAL => qw/void io/],
);

see warnings for more info about lexical warnings. πŸ“š

⭐ hint_bits, warning_bits

these two parameters let you specify the ambient pragmas in the format used by the special variables $^H and "${^WARNING_BITS}".

they exist principally so you can write code like this:

{ my ($hint_bits, $warning_bits);
BEGIN {($hint_bits, $warning_bits) = ($^H, ${^WARNING_BITS})}
$deparser->ambient_pragmas (
    hint_bits    => $hint_bits,
    warning_bits => $warning_bits,
    '$['         => 0 + $[
); }

which specifies that the ambient pragmas are exactly the ones in scope at the point of calling. but bestie, also go look at "ambient_pragmas_from_caller".

🫢 %^H

this parameter is used to specify the ambient pragmas that are stored in the special hash %^H.

🌟 ambient_pragmas_from_caller 🌟

$deparse->ambient_pragmas_from_caller()

a convenient little shortcut that sets the hints and warnings ambient pragmas to the ones from the immediately calling code. it uses the caller function to figure out the hints and warnings bits in effect at the callsite of this method, and sets those as the deparser's ambient settings. chef's kiss, effortless. 😌

πŸ’– coderef2text πŸ’–

$body = $deparse->coderef2text(\&func)
$body = $deparse->coderef2text(sub ($$) { ... })

returns source code for the body of a subroutine β€” that's a block, optionally preceded by a prototype in parens β€” given a reference to the sub.

because a subroutine can have no names, or more than one name, this method does not return a complete subroutine definition. so if you wanna eval the result, you should prepend "sub subname ", or "sub " for an anonymous function constructor. and unless the sub was defined in the main:: package, the code will include a package declaration.

normally B::Deparse will emit code that includes the feature pragma if it's required to enable features used in the fragment that follows. however, since coderef2text emits only the body of a subroutine and expects the caller to prepend the sub and optional name onto the beginning of it, it won't have the opportunity to emit a "use feature 'signatures'" if the subroutine uses a signature, and the signatures feature isn't enabled in the ambient pragmas. rip to that edge case. πŸ™ˆ

and in that particular situation β€” a sub using the "signatures" feature to parse its arguments, being passed to coderef2text while the feature is not enabled in "ambient_pragmas" β€” B::Deparse will attempt to emit pure-perl code that emulates the behaviour of the signature as closely as possible. and this is done on a best-effort basis, okay? it is not guaranteed to perfectly capture the semantics of the signature's behaviour β€” only to offer a human-readable suggestion as to what it might do. plus it is not guaranteed to be able to reproduce every possible behaviour of signatures in future versions of Perl. it may be that a future version introduces a behaviour that simply doesn't have a tidy way to express it in this pure-perl emulation code without using the "signatures" feature.

so if this matters to you: make sure you use the "ambient_pragmas" or "ambient_pragmas_from_caller" method to enable the "signatures" feature, ensuring B::Deparse will use it to deparse subroutines that use signatures. do that and you're golden. πŸ’›


πŸ’€ BUGS πŸ’€

bestie. sit down. we gotta talk about the flaws. it's giving "flawed but iconic."
  • the only pragmas that are completely supported are: "use warnings", "use strict", "use bytes", "use integer" and "use feature".

excepting those listed above, we're currently unable to guarantee that B::Deparse will produce a pragma at the correct point in the program. (specifically: pragmas at the beginning of a block often appear right before the start of the block instead.) and since the effects of pragmas are often lexically scoped, this can mean the pragma holds sway over a different portion of the program than in the input file. 😭

  • in fact, the above is a specific instance of a more general problem: we can't guarantee to produce "BEGIN" blocks or "use" declarations in exactly the right place. so if you use a module that affects compilation β€” like by over-riding keywords, overloading constants, or whatever β€” then the output code might not work as intended. πŸ’€
  • some constants don't print correctly either with or without -d. for instance, neither B::Deparse nor Data::Dumper know how to print dual-valued scalars correctly, as in:
use constant E2BIG => ($!=7); $y = E2BIG; print $y, 0+$y;

use constant H => { "#" => 1 }; H->{"#"};
  • an input file that uses source filtering probably won't be deparsed into runnable code, because it will still include the use declaration for the source filtering module β€” even though the code that gets produced is already ordinary Perl that shouldn't be filtered again. awkward. πŸ™ƒ
  • optimized-away statements are rendered as '???'. this includes statements that have a compile-time side-effect, like this obscure little number:
my $x if 0;

which is not, consequently, deparsed correctly.

foreach my $i (@_) { 0 }
=>
foreach my $i (@_) { '???' }
  • lexical (my) variables declared in scopes external to a subroutine appear in "coderef2text" output text as package variables. this is a tricky problem, since perl has no native facility for referring to a lexical variable defined within a different scope β€” although PadWalker is a good start.

see also Data::Dump::Streamer, which combines B::Deparse and PadWalker to serialize closures properly. closure girls, assemble. 🫢

  • there are probably many more bugs on non-ASCII platforms (EBCDIC). of course there are. 🫠

πŸ‘‘ AUTHOR πŸ‘‘

Stephen McCamant <smcc@CSUA.Berkeley.EDU>, based on an earlier version by Malcolm Beattie <mbeattie@sable.ox.ac.uk>, with contributions from Gisle Aas, James Duncan, Albert Dvornik, Robin Houston, Dave Mitchell, Hugo van der Sanden, Gurusamy Sarathy, Nick Ing-Simmons, and Rafael Garcia-Suarez.


and that's the whole page, bestie πŸŽ€ this was B::Deparse from perl v5.44.0, dated 2026-10-17 β€” go forth, deparse responsibly, and remember: the vibe changes, the facts don't. βœ¨πŸ’–πŸ‘‘

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms