B(3perl)
π NAME π
so bestie, meet B β The Perl Compiler Backend π§ β¨ (it's B(3perl), from the Perl Programmers Reference Guide, iykyk). fr fr, this is the module that lets your perl program go digging around in its own guts π
β¨ SYNOPSIS β¨
use B;
that's it. that's the whole vibe check. π
π¦ DESCRIPTION π¦
okay so the B module ships a whole lil family of classes that let a Perl program delve into its own innards π«£π«Ά. it's literally the module used to implement the "backends" of the Perl compiler.
and no, you do NOT need to know this module to use the compiler β for the user-visible part you want the O module instead, bestie π
B is for the girlies who wanna write new compiler backends. and heads up π this documentation assumes you already know a fair amount about perl's internals, including stuff like SVs, OPs, and the internal symbol table and syntax tree of a program. so like... not a beginner read, no cap. π
π OVERVIEW π
the B module has a set of utility functions for querying the current state of the Perl interpreter π΅οΈβοΈβ¨. typically these functions return objects from the B::SV and B::OP classes, or their derived classes. and those classes in turn define methods for querying the resulting objects about their own internal state. it's giving object-oriented introspection, and honestly? obsessed. π
πΈ Utility Functions πΈ
the B module exports a whole variety of functions: some are simple utility functions, and the others hand your Perl program a way to grab an initial "handle" on an internal object. π
π§ Functions Returning B::SV, B::AV, B::HV, and B::CV objects
for the deets on the class hierarchy of these objects and the methods you can call on them, scroll down to "OVERVIEW OF CLASSES" and "SV-RELATED CLASSES" below π
sv_undefβ returns the SV object corresponding to the C variablesv_undef. πsv_yesβ returns the SV object corresponding to the C variablesv_yes. βsv_noβ returns the SV object corresponding to the C variablesv_no. βsvref_2object(SVREF)β takes a reference to any Perl value, and turns the referred-to value into an object in the appropriateB::OP-derived orB::SV-derived class. apart from functions likemain_root, this is the primary way to get an initial "handle" on an internal perl data structure, which you can then follow with the other access methods. π«Ά
β οΈ real talk: the returned object is only valid as long as the underlying OPs and SVs continue to exist. do NOT try to use the object after the underlying structures are freed, bestie. that's a crunchy glitch situation. π
amagic_generationβ returns the SV object corresponding to the C variableamagic_generation. as of Perl 5.18, this is just an alias toPL_na, so its value is meaningless. π like, don't bother, it's giving nothing.init_avβ returns the AV object (i.e. in classB::AV) representingINITblocks. π±check_avβ returns the AV object (i.e. in classB::AV) representingCHECKblocks. πunitcheck_avβ returns the AV object (i.e. in classB::AV) representingUNITCHECKblocks. π§ͺbegin_avβ returns the AV object (i.e. in classB::AV) representingBEGINblocks. πend_avβ returns the AV object (i.e. in classB::AV) representingENDblocks. πcomppadlistβ returns thePADLISTobject (i.e. in classB::PADLIST) of the global comppadlist. in Perl 5.16 and earlier it returns an AV object (classB::AV). ποΈregex_padavβ only when perl was compiled with ithreads. π§΅main_cvβ returns the (faked) CV corresponding to the main part of the Perl program. π main character energy fr.
π Functions for Examining the Symbol Table
walksymtable(SYMREF, METHOD, RECURSE, PREFIX)β walk the symbol table starting at SYMREF and call METHOD on each symbol (aB::GVobject) visited. when the walk reaches package symbols (such asFoo::) it invokes RECURSE, passing in the symbol name, and only recurses into the package if that sub returns true. β
PREFIX is the name of the SYMREF you're walking. πΆβοΈ
for example:
# Walk CGI's symbol table calling print_subs on each symbol.
# Recurse only into CGI::Util::
walksymtable(\%CGI::, 'print_subs',
sub { $_[0] eq 'CGI::Util::' }, 'CGI::');
print_subs() is a B::GV method you have declared, bestie. also peep "B::GV Methods" below π
π₯ Functions Returning B::OP objects or for walking op trees
for the deets on the class hierarchy of these objects and the methods you can call on them, look below at "OVERVIEW OF CLASSES" and "OP-RELATED CLASSES" π
main_rootβ returns the root op (i.e. an object in the appropriateB::OP-derived class) of the main part of the Perl program. π³main_startβ returns the starting op of the main part of the Perl program. πwalkoptree(OP, METHOD)β does a tree-walk of the syntax tree based at OP and calls METHOD on each op it visits. each node is visited before its children. ifwalkoptree_debug(see below π) has been called to turn debugging on, then the methodwalkoptree_debugis called on each op before METHOD is called. πβ¨walkoptree_debug(DEBUG)β returns the current debugging flag forwalkoptree. if the optional DEBUG argument is non-zero, it sets the debugging flag to that. see the description ofwalkoptreeabove for what the debugging flag actually does. πΉοΈ
π Miscellaneous Utility Functions
ppname(OPNUM)β return the PP function name (e.g.pp_add) of op number OPNUM. π·οΈhash(STR)β returns a string in the form"0x..."representing the value of the internal hash function used by perl on string STR. #οΈβ£cast_I32(I)β casts I to the internal I32 type used by that perl. πͺminus_cβ does the equivalent of the-ccommand-line option. obviously, this is only useful in aBEGINblock, or else the flag is set too late. β°πcstring(STR)β returns a double-quote-surrounded escaped version of STR which can be used as a string in C source code. π»perlstring(STR)β returns a double-quote-surrounded escaped version of STR which can be used as a string in Perl source code. πͺsafename(STR)β returns the string with the first character modified if it is a control character. it converts it to^Xformat first, so that"\cG"becomes"^G". this is used internally byB::GV::SAFENAME, but you can call it directly. πclass(OBJ)β returns the class of an object without the part of the classname preceding the first::. this is used to turnB::UNOPintoUNOP, for example. π·οΈthreadsv_namesβ this used to provide support for the old 5.005 threading module. it now does nothing. π ghost of modules past.
π Exported utility variables
@optype
my $op_type = $optype[$op_type_num];
a simple mapping of the op type number to its type (like 'COP' or 'BINOP'). πΊοΈ
@specialsv_name
my $sv_name = $specialsv_name[$sv_index];
certain SV types are considered 'special'. they're represented by B::SPECIAL and are referred to by a number from the specialsv_list. this array maps that number back to the name of the SV (like 'Nullsv' or '&PL_sv_undef'). β
π OVERVIEW OF CLASSES π
okay so the C structures used by Perl's internals to hold SV and OP information (PVIV, AV, HV, ..., OP, SVOP, UNOP, ...) are modelled on a class hierarchy π, and the B module gives you access to them via a true object hierarchy. structure fields which point to other objects (whether types of SV or types of OP) are represented by the B module as Perl objects of the appropriate class. π
the bulk of the B module is literally the methods for accessing fields of these structures. π§
β οΈ heads up bestie: all access is read-only. you cannot modify the internals by using this module, periodt. π« also β theB::OPandB::SVobjects created by this module are only valid for as long as the underlying objects exist; their creation doesn't increase the reference counts of the underlying objects. trying to access the fields of a freed object will give you incomprehensible results, or worse. ππ don't do it.
π¦ SV-RELATED CLASSES π¦
B::IV, B::NV, B::PV, B::PVIV, B::PVNV, B::PVMG, B::PVLV, B::AV, B::HV, B::CV, B::GV, B::FM, B::IO. β¨ these classes correspond in the obvious way to the underlying C structures of similar names. and the inheritance hierarchy mimics the underlying C "inheritance":
B::SV
|
+------------+------------+
| | |
B::PV B::IV B::NV
/ \ / /
/ \ / /
B::INVLIST B::PVIV /
\ /
\ /
\ /
B::PVNV
|
|
B::PVMG
|
+-------+-------+---+---+-------+-------+
| | | | | |
B::AV B::GV B::HV B::CV B::IO B::REGEXP
| |
| |
B::PVLV B::FM
access methods correspond to the underlying C macros for field access, usually with the leading "class indication" prefix removed (Sv, Av, Hv, ...). πͺ the leading prefix is only left in cases where its removal would cause a clash in method name. for example, GvREFCNT stays as-is since its abbreviation would clash with the "superclass" method REFCNT (corresponding to the C function SvREFCNT). π
π B::SV Methods π
REFCNTFLAGSIsBOOLβ returns true if the SV is a boolean (true or false). you can then useTRUEto check if the value is true or false. π―
my $something = ( 1 == 1 ) # boolean true
|| ( 1 == 0 ) # boolean false
|| 42 # IV true
|| 0; # IV false
my $sv = B::svref_2object(\$something);
say q[Not a boolean value]
if ! $sv->IsBOOL;
say q[This is a boolean with value: true]
if $sv->IsBOOL && $sv->TRUE_nomg;
say q[This is a boolean with value: false]
if $sv->IsBOOL && ! $sv->TRUE_nomg;
object_2svrefβ returns a reference to the regular scalar corresponding to thisB::SVobject. in other words, this method is the inverse operation to thesvref_2object()subroutine. π this scalar and other data it points at should be considered read-only: modifying them is neither safe nor guaranteed to have a sensible effect. πTRUEβ returns a boolean indicating whether Perl would evaluate the SV as true or false. π§
β οΈ warning: this call performs 'get' magic. if you only want to check the nature of this SV, use the TRUE_nomg helper instead. πͺ
this is an alias for SvTRUE($sv). π
TRUE_nomgβ checks if the value is true, and it does not do 'get' magic, okay? Returns a boolean telling you whether Perl would look at that SV and go "yeah, true" or "nah, false". It's literally just an alias forSvTRUE_nomg($sv). π
π B::IV Methods π
IVβ hands you the value of the IV, read as a signed integer. β οΈ Heads up bestie, this one will straight-up mislead you ifFLAGS & SVf_IVisUV. Maybe you actually want theint_valuemethod instead? Just saying. πIVXUVXint_valueβ returns the value of the IV as an integer, and the glow-up here is that it differs fromIVby returning the correct value no matter whether it's stored signed or unsigned. She's reliable, we stan. β¨needs64bitspackiv
πΈ B::NV Methods πΈ
NVNVXCOP_SEQ_RANGE_LOWCOP_SEQ_RANGE_HIGHβ okay so these last two? They're only valid for pad name SVs, no cap. And plot twist: they only lived in theB::NVclass before Perl 5.22. In 5.22 they got moved to theB::PADNAMEclass. She relocated, respect the journey. π¦
π B::RV Methods π
RV
β B::PV Methods β
PVβ this is THE one you usually want, periodt. It builds a string using the length and offset info sitting in the struct: for ordinary scalars it returns the string you'd actually see from Perl, even if it's hiding null characters in there. Iconic.RVβ same asB::RV::RV, except it willdie()if the PV isn't a reference. So like, don't play with her.PVXβ this method is less often useful, ngl. It assumes the string stored in the struct is null-terminated and just disregards the length info entirely. π
But! It's the appropriate method to use if you need to grab the name of a lexical variable out of a padname array. Lexical variable names are always stored with a null terminator, and the length field (CUR) is overloaded for other purposes, so you literally can't rely on it here. iykyk.
CURβ returns the internal length field, which is the number of internal bytes, not necessarily the number of logical characters. (bytes β characters, we been knew π)LENβ returns the number of bytes allocated (viamalloc) for storing the string. This is0if the scalar does not "own" the string.
π«Ά B::PVMG Methods π«Ά
MAGICSvSTASH
π₯ B::MAGIC Methods π₯
MOREMAGICprecompβ only valid on r-magic, and it returns the string that generated the regexp. π§PRIVATETYPEFLAGSOBJβ willdie()if you call it on r-magic. She said no. πPTRREGEXβ only valid on r-magic; returns the integer value of the REGEX stored in the MAGIC.
π B::INVLIST Methods π
prev_indexβ returns the cache result of the previousinvlist_search()(internal usage, so don't get too attached bestie).is_offsetβ returns a boolean value (0or1) so you know if the invlist is using an offset. When false, the list begins with the code pointU+0000. When true, the list begins with the following elements.array_lenβ returns an integer with the size of the array used to define the invlist.get_invlist_arrayβ returns a list of integers representing the array the invlist uses. β οΈ Note: this cannot be used while you're in the middle of iterating on an invlist, and it croaks. So like, wait your turn.
π B::PVLV Methods π
TARGOFFTARGLENTYPETARG
β¨ B::BM Methods β¨
USEFULPREVIOUSRARETABLE
π B::REGEXP Methods π
REGEXprecompqr_anoncvcompflagsβ the last two were added in Perl 5.22. π
π¦ B::GV Methods π¦
is_emptyβ returns TRUE if the GP field of the GV isNULL.NAMESAFENAMEβ returns the name of the glob, but if the first character of the name is a control character, it converts it to^Xfirst. So*^Gwould give you back"^G"rather than"\cG". Cute, right?
It's useful if you wanna print out the name of a variable. And if you keep yourself restricted to globs that exist at compile-time, the result ought to be unambiguous β because code like "${"^G"} = 1" compiles as two ops: a constant string and a dereference (rv2gv). Which means the glob gets created at runtime. Sneaky.
If you're working with globs at runtime and you need to disambiguate *^G from *{"^G"}, then you should use the raw NAME method. No shortcuts bestie. π
STASHSVIOFORMAVHVEGVCVCVGENLINEFILEFILEGVGvREFCNTFLAGSGPFLAGSβ this last one is only present in perl 5.22.0 and higher.
πΈ B::IO Methods πΈ
B::IO objects derive from IO objects, so honestly you'll get more info from the IO object itself. Periodt.
For example:
$gvio = B::svref_2object(\*main::stdin)->IO;
$IO = $gvio->object_2svref();
$fd = $IO->fileno();
LINESPAGEPAGE_LENLINES_LEFTTOP_NAMETOP_GVFMT_NAMEFMT_GVBOTTOM_NAMEBOTTOM_GVSUBPROCESSIoTYPEβ a character symbolizing the type of IO Handle:
- STDIN/OUT
I STDIN/OUT/ERR
< read-only
> write-only
a append
+ read and write
s socket
| pipe
I IMPLICIT
# NUMERIC
space closed handle
\0 closed internal handle
IoFLAGSIsSTDβ takes one argument ('stdin'|'stdout'|'stderr') and returns true if the IoIFP of the object equals the handle whose name you passed in. Like,$io->IsSTD('stderr')is true ifIoIFP($io) == PerlIO_stderr(). Simple as. β
π B::AV Methods π
FILLMAXARRAYARRAYeltβ likeARRAY, but it takes an index as an argument so you get just one element instead of a whole list. She's efficient. β¨
β B::CV Methods β
STASHSTARTROOTGVFILEDEPTHPADLISTβ returns aB::PADLISTobject.OUTSIDEOUTSIDE_SEQXSUBXSUBANYβ for constant subroutines, returns the constant SV the subroutine gives back.CvFLAGSconst_svNAME_HEKβ returns the name of a lexical sub, otherwiseundef.
π₯ B::HV Methods π₯
FILLMAXKEYSRITERNAMEARRAY
π OP-RELATED CLASSES π
B::OP, B::UNOP, B::UNOP_AUX, B::BINOP, B::LOGOP, B::LISTOP, B::PMOP, B::SVOP, B::PADOP, B::PVOP, B::LOOP, B::COP, B::METHOP.
These classes correspond in the obvious way to the underlying C structures with similar names. And the inheritance hierarchy mimics the underlying C "inheritance", like, exactly:
B::OP
|
+----------+---------+--------+-------+---------+
| | | | | |
B::UNOP B::SVOP B::PADOP B::COP B::PVOP B::METHOP
|
+---+---+---------+
| | |
B::BINOP B::LOGOP B::UNOP_AUX
|
|
B::LISTOP
|
+---+---+
| |
B::LOOP B::PMOP
Access methods correspond to the underlying C structure field names, with the leading "class indication" prefix (op_) removed. Clean. π§Ό
π B::OP Methods π
These methods get the values of similarly named fields inside the OP data structure. See the top of op.h for more info, bestie. π
nextsiblingparentβ returns the OP's parent. If it has no parent, or if your perl wasn't built with-DPERL_OP_PARENT, it returnsNULL.
β οΈ And like, note this: the global variable $B::OP::does_parent is undefined on older perls that don't support the parent method. It's defined but false on perls that support the method but were built without -DPERL_OP_PARENT. And it's true otherwise. Three moods, okay? π
nameβ returns the op name as a string (e.g.add,rv2av).ppaddrβ returns the function name as a string (e.g.PL_ppaddr[OP_ADD],PL_ppaddr[OP_RV2AV]).descβ returns the op description from the global C PL_op_desc array (e.g.addition,array deref).targtypeoptflagsprivatespare
π B::UNOP Method π
first
π¦ B::UNOP_AUX Methods (since 5.22) π¦
aux_list(cv)β returns a list of the elements of the op's aux data structure, or a null list if there's no aux. What you get back depends on the object's type, but it'll typically be a collection ofB::IV,B::GV, etc. objects.cvis theB::CVobject representing the sub the op is contained within.string(cv)β returns a textual representation of the object (likely to be useful for deparsing and debugging), or an empty string if the op type doesn't support this.cvis theB::CVobject representing the sub the op is contained within.
πΈ B::BINOP Method πΈ
last
π B::LOGOP Method π
other
β B::LISTOP Method β
children
π B::PMOP Methods π
pmreplrootpmreplstartpmflagsprecomppmoffsetβ only when perl was compiled with ithreads.code_listβ since perl 5.17.1.pmregexpβ added in perl 5.22, this method returns theB::REGEXPassociated with the op. And the fun part: while PMOPs don't actually havepmregexpfields under threaded builds, this method returns the regexp under threads anyway. For convenience. She's doing the most so you don't have to. π
π«Ά B::SVOP Methods π«Ά
svgv
π₯ B::PADOP Method π₯
padix
π B::PVOP Method π
pv
π¦ B::LOOP Methods π¦
redoopnextoplastop
π B::COP Methods π
The B::COP class is used for nextstate and dbstate ops. And as of Perl 5.22, it's also used for null ops that started out as COPs. Glow-up era. β¨
labelstashstashpvstashoff(threaded only)filecop_seqlinewarningsiohintshints_hash
β B::METHOP Methods (Since Perl 5.22) β
firstmeth_sv
π PAD-RELATED CLASSES π
Perl 5.18 introduced a new class, B::PADLIST, returned by B::CV's PADLIST method.
Perl 5.22 introduced the B::PADNAMELIST and B::PADNAME classes.
π B::PADLIST Methods π
MAXARRAYβ a list of pads. The first one is aB::PADNAMELISTcontaining the names. The rest are currentlyB::AVobjects, but that could change in future versions. So like, don't get too comfy. πARRAYeltβ likeARRAY, but it takes an index as an argument to get just one element instead of a list of all of them.NAMESβ this method, introduced in 5.22, returns theB::PADNAMELIST. It's equivalent toARRAYeltwith a0argument.REFCNTidβ this method, introduced in 5.22, returns an ID shared by clones of the same padlist.outidβ this method, also added in 5.22, returns the ID of the outer padlist.
π B::PADNAMELIST Methods π
MAXARRAYARRAYeltβ these two methods return the pad names, usingB::SPECIALobjects for null pointers andB::PADNAMEobjects otherwise.REFCNT
π B::PADNAME Methods π
okay bestie, these are the little accessor methods you get on a B::PADNAME object π every lexical name in a pad has one of these, and here's literally everything you can ask it:
PVβ the string value, the plain little pointer-to-string vibe β¨PVXβ the string value but make it longer (thePVXflavour, iykyk)LENβ how long that string is π’REFCNTβ how many things are pointing at it rnGENβ the generation number, as one doesFLAGSβ the flag situation π© For backward-compatibility, if thePADNAMEt_OUTERflag is set, the FLAGS method adds theSVf_FAKEflag, too. (yes, extra flag for the old-school girlies, that's the deal)TYPEβ aB::HVobject representing the stash for a typed lexical. no cap πSvSTASHβ a backward-compatibility alias for TYPE. same energy, older name π«ΆOURSTASHβ aB::HVobject representing the stash for'our'variables πPROTOCVβ the prototype CV for a'my'sub πCOP_SEQ_RANGE_LOWβ sequence numbers representing the scope within which a lexical is visible. Meaningless ifPADNAMEt_OUTERis set. β οΈCOP_SEQ_RANGE_HIGHβ Sequence numbers representing the scope within which a lexical is visible. Meaningless ifPADNAMEt_OUTERis set. β οΈPARENT_PAD_INDEXβ Only meaningful ifPADNAMEt_OUTERis set. like, don't even look at it otherwise bestie πPARENT_FAKELEX_FLAGSβ Only meaningful ifPADNAMEt_OUTERis set. same rule, girl πIsUndefβ Returns a boolean value to check if the padname isPL_padname_undef. cute little true/false check β¨
π¦ $B::overlay π¦
okay so the optree is read-only, right? like, hands off, no touching π BUT there's this little overlay facility that lets you override what values the various B::*OP methods return for a particular op. it's giving "we're not editing the optree, we're just lying to it" π
Here's the tea: $B::overlay should be set to reference a two-deep hash β indexed by OP address first, then by method name. Whenever an op method gets called, the value sitting in that hash is returned if it exists. easy! β¨
And guess who uses this? B::Deparse, to "undo" some optimisations π iconic behaviour fr fr.
For example:
local $B::overlay = {};
...
if ($op->name eq "foo") {
$B::overlay->{$$op} = {
name => 'bar',
next => $op->next->next,
};
}
...
$op->name # returns "bar"
$op->next # returns the next op but one
like, look at her go π you literally told it bar and it said bar, periodt.
π AUTHOR π
Malcolm Beattie, "mbeattie@sable.ox.ac.uk" β yes bestie, a whole legend wrote this for us, show some respect π«Ά
and that's the whole page!! this is perl v5.44.0, dated 2026-10-17, from the B(3perl) manual πΈ you literally read the entire thing, slay πβ¨π go touch some grass (or, y'know, go deparse something) π¦
π¦ 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