{
    "content": [
        {
            "type": "text",
            "text": "# PERLGUTS (man)\n\n## NAME\n\nperlguts - Introduction to the Perl API\n\n## DESCRIPTION\n\nThis document attempts to describe how to use the Perl API, as well as to provide some info\non the basic workings of the Perl core.  It is far from complete and probably contains many\nerrors.  Please refer any questions or comments to the author below.\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION**\n- **Variables** (24 subsections)\n- **Subroutines** (10 subsections)\n- **PerlIO** (32 subsections)\n- **Stacks** (11 subsections)\n- **AUTHORS**\n- **SEE ALSO**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "PERLGUTS",
        "section": "",
        "mode": "man",
        "summary": "perlguts - Introduction to the Perl API",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "Variables",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Datatypes",
                        "lines": 8
                    },
                    {
                        "name": "What is an \"IV\"?",
                        "lines": 21
                    },
                    {
                        "name": "Working with SVs",
                        "lines": 279
                    },
                    {
                        "name": "Offsets",
                        "lines": 52
                    },
                    {
                        "name": "What's Really Stored in an SV?",
                        "lines": 25
                    },
                    {
                        "name": "Working with AVs",
                        "lines": 59
                    },
                    {
                        "name": "Working with HVs",
                        "lines": 79
                    },
                    {
                        "name": "Hash API Extensions",
                        "lines": 40
                    },
                    {
                        "name": "AVs, HVs and undefined values",
                        "lines": 48
                    },
                    {
                        "name": "References",
                        "lines": 39
                    },
                    {
                        "name": "Blessed References and Class Objects",
                        "lines": 57
                    },
                    {
                        "name": "Creating New Variables",
                        "lines": 29
                    },
                    {
                        "name": "Reference Counts and Mortality",
                        "lines": 104
                    },
                    {
                        "name": "Stashes and Globs",
                        "lines": 48
                    },
                    {
                        "name": "I/O Handles",
                        "lines": 49
                    },
                    {
                        "name": "Double-Typed SVs",
                        "lines": 35
                    },
                    {
                        "name": "Read-Only Values",
                        "lines": 19
                    },
                    {
                        "name": "Copy on Write",
                        "lines": 21
                    },
                    {
                        "name": "Magic Variables",
                        "lines": 20
                    },
                    {
                        "name": "Assigning Magic",
                        "lines": 53
                    },
                    {
                        "name": "Magic Virtual Tables",
                        "lines": 187
                    },
                    {
                        "name": "Finding Magic",
                        "lines": 19
                    },
                    {
                        "name": "Understanding the Magic of Tied Hashes and Arrays",
                        "lines": 71
                    },
                    {
                        "name": "Localizing changes",
                        "lines": 124
                    }
                ]
            },
            {
                "name": "Subroutines",
                "lines": 1,
                "subsections": [
                    {
                        "name": "XSUBs and the Argument Stack",
                        "lines": 52
                    },
                    {
                        "name": "Autoloading with XSUBs",
                        "lines": 18
                    },
                    {
                        "name": "Calling Perl Routines from within C Programs",
                        "lines": 37
                    },
                    {
                        "name": "Putting a C value on Perl stack",
                        "lines": 43
                    },
                    {
                        "name": "Scratchpads",
                        "lines": 18
                    },
                    {
                        "name": "Scratchpads and recursion",
                        "lines": 15
                    },
                    {
                        "name": "Memory Allocation",
                        "lines": 1
                    },
                    {
                        "name": "Allocation",
                        "lines": 21
                    },
                    {
                        "name": "Reallocation",
                        "lines": 8
                    },
                    {
                        "name": "Moving",
                        "lines": 9
                    }
                ]
            },
            {
                "name": "PerlIO",
                "lines": 9,
                "subsections": [
                    {
                        "name": "Compiled code",
                        "lines": 1
                    },
                    {
                        "name": "Code tree",
                        "lines": 24
                    },
                    {
                        "name": "Examining the tree",
                        "lines": 80
                    },
                    {
                        "name": "Compile pass 1: check routines",
                        "lines": 19
                    },
                    {
                        "name": "Compile pass 1a: constant folding",
                        "lines": 7
                    },
                    {
                        "name": "Compile pass 2: context propagation",
                        "lines": 10
                    },
                    {
                        "name": "Compile pass 3: peephole optimization",
                        "lines": 39
                    },
                    {
                        "name": "Pluggable runops",
                        "lines": 13
                    },
                    {
                        "name": "Compile-time scope hooks",
                        "lines": 51
                    },
                    {
                        "name": "Examining internal data structures with the \"dump\" functions",
                        "lines": 30
                    },
                    {
                        "name": "How multiple interpreters and concurrency are supported",
                        "lines": 98
                    },
                    {
                        "name": "So what happened to dTHR?",
                        "lines": 5
                    },
                    {
                        "name": "How do I use all this in extensions?",
                        "lines": 95
                    },
                    {
                        "name": "Should I do anything special if I call perl from multiple threads?",
                        "lines": 32
                    },
                    {
                        "name": "Internal Functions",
                        "lines": 25
                    },
                    {
                        "name": "Formatted Printing of IVs, UVs, and NVs",
                        "lines": 23
                    },
                    {
                        "name": "Formatted Printing of SVs",
                        "lines": 26
                    },
                    {
                        "name": "Formatted Printing of Strings",
                        "lines": 40
                    },
                    {
                        "name": "Pointer-To-Integer and Integer-To-Pointer",
                        "lines": 26
                    },
                    {
                        "name": "Exception Handling",
                        "lines": 28
                    },
                    {
                        "name": "Source Documentation",
                        "lines": 18
                    },
                    {
                        "name": "Backwards compatibility",
                        "lines": 17
                    },
                    {
                        "name": "Unicode Support",
                        "lines": 3
                    },
                    {
                        "name": "What is Unicode, anyway?",
                        "lines": 23
                    },
                    {
                        "name": "How can I recognise a UTF-8 string?",
                        "lines": 12
                    },
                    {
                        "name": "How does UTF-8 represent Unicode characters?",
                        "lines": 60
                    },
                    {
                        "name": "How does Perl store UTF-8 strings?",
                        "lines": 63
                    },
                    {
                        "name": "How do I pass a Perl string to a C library?",
                        "lines": 49
                    },
                    {
                        "name": "How do I convert a string to UTF-8?",
                        "lines": 19
                    },
                    {
                        "name": "How do I compare strings?",
                        "lines": 10
                    },
                    {
                        "name": "Is there anything else I need to know?",
                        "lines": 18
                    },
                    {
                        "name": "Custom Operators",
                        "lines": 77
                    }
                ]
            },
            {
                "name": "Stacks",
                "lines": 7,
                "subsections": [
                    {
                        "name": "Value Stack",
                        "lines": 42
                    },
                    {
                        "name": "Mark Stack",
                        "lines": 50
                    },
                    {
                        "name": "Temporaries Stack",
                        "lines": 29
                    },
                    {
                        "name": "Save Stack",
                        "lines": 48
                    },
                    {
                        "name": "Scope Stack",
                        "lines": 21
                    },
                    {
                        "name": "Dynamic Scope and the Context Stack",
                        "lines": 3
                    },
                    {
                        "name": "Introduction to the context stack",
                        "lines": 45
                    },
                    {
                        "name": "Pushing contexts",
                        "lines": 97
                    },
                    {
                        "name": "Popping contexts",
                        "lines": 105
                    },
                    {
                        "name": "Redoing contexts",
                        "lines": 6
                    },
                    {
                        "name": "Slab-based operator allocation",
                        "lines": 82
                    }
                ]
            },
            {
                "name": "AUTHORS",
                "lines": 7,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 5,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlguts - Introduction to the Perl API\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This document attempts to describe how to use the Perl API, as well as to provide some info\non the basic workings of the Perl core.  It is far from complete and probably contains many\nerrors.  Please refer any questions or comments to the author below.\n",
                "subsections": []
            },
            "Variables": {
                "content": "",
                "subsections": [
                    {
                        "name": "Datatypes",
                        "content": "Perl has three typedefs that handle Perl's three main data types:\n\nSV  Scalar Value\nAV  Array Value\nHV  Hash Value\n\nEach typedef has specific routines that manipulate the various data types.\n"
                    },
                    {
                        "name": "What is an \"IV\"?",
                        "content": "Perl uses a special typedef IV which is a simple signed integer type that is guaranteed to be\nlarge enough to hold a pointer (as well as an integer).  Additionally, there is the UV, which\nis simply an unsigned IV.\n\nPerl also uses several special typedefs to declare variables to hold integers of (at least) a\ngiven size.  Use I8, I16, I32, and I64 to declare a signed integer variable which has at\nleast as many bits as the number in its name.  These all evaluate to the native C type that\nis closest to the given number of bits, but no smaller than that number.  For example, on\nmany platforms, a \"short\" is 16 bits long, and if so, I16 will evaluate to a \"short\".  But on\nplatforms where a \"short\" isn't exactly 16 bits, Perl will use the smallest type that\ncontains 16 bits or more.\n\nU8, U16, U32, and U64 are to declare the corresponding unsigned integer types.\n\nIf the platform doesn't support 64-bit integers, both I64 and U64 will be undefined.  Use IV\nand UV to declare the largest practicable, and \"\"WIDESTUTYPE\" in perlapi\" for the absolute\nmaximum unsigned, but which may not be usable in all circumstances.\n\nA numeric constant can be specified with \"\"INT16C\"\" in perlapi, \"\"UINTMAXC\"\" in perlapi,\nand similar.\n"
                    },
                    {
                        "name": "Working with SVs",
                        "content": "An SV can be created and loaded with one command.  There are five types of values that can be\nloaded: an integer value (IV), an unsigned integer value (UV), a double (NV), a string (PV),\nand another scalar (SV).  (\"PV\" stands for \"Pointer Value\".  You might think that it is\nmisnamed because it is described as pointing only to strings.  However, it is possible to\nhave it point to other things.  For example, it could point to an array of UVs.  But, using\nit for non-strings requires care, as the underlying assumption of much of the internals is\nthat PVs are just for strings.  Often, for example, a trailing \"NUL\" is tacked on\nautomatically.  The non-string use is documented only in this paragraph.)\n\nThe seven routines are:\n\nSV*  newSViv(IV);\nSV*  newSVuv(UV);\nSV*  newSVnv(double);\nSV*  newSVpv(const char*, STRLEN);\nSV*  newSVpvn(const char*, STRLEN);\nSV*  newSVpvf(const char*, ...);\nSV*  newSVsv(SV*);\n\n\"STRLEN\" is an integer type (\"Sizet\", usually defined as \"sizet\" in config.h) guaranteed to\nbe large enough to represent the size of any string that perl can handle.\n\nIn the unlikely case of a SV requiring more complex initialization, you can create an empty\nSV with newSV(len).  If \"len\" is 0 an empty SV of type NULL is returned, else an SV of type\nPV is returned with len + 1 (for the \"NUL\") bytes of storage allocated, accessible via SvPVX.\nIn both cases the SV has the undef value.\n\nSV *sv = newSV(0);   /* no storage allocated  */\nSV *sv = newSV(10);  /* 10 (+1) bytes of uninitialised storage\n* allocated */\n\nTo change the value of an already-existing SV, there are eight routines:\n\nvoid  svsetiv(SV*, IV);\nvoid  svsetuv(SV*, UV);\nvoid  svsetnv(SV*, double);\nvoid  svsetpv(SV*, const char*);\nvoid  svsetpvn(SV*, const char*, STRLEN)\nvoid  svsetpvf(SV*, const char*, ...);\nvoid  svvsetpvfn(SV*, const char*, STRLEN, valist *,\nSV , Sizet, bool *);\nvoid  svsetsv(SV*, SV*);\n\nNotice that you can choose to specify the length of the string to be assigned by using\n\"svsetpvn\", \"newSVpvn\", or \"newSVpv\", or you may allow Perl to calculate the length by using\n\"svsetpv\" or by specifying 0 as the second argument to \"newSVpv\".  Be warned, though, that\nPerl will determine the string's length by using \"strlen\", which depends on the string\nterminating with a \"NUL\" character, and not otherwise containing NULs.\n\nThe arguments of \"svsetpvf\" are processed like \"sprintf\", and the formatted output becomes\nthe value.\n\n\"svvsetpvfn\" is an analogue of \"vsprintf\", but it allows you to specify either a pointer to\na variable argument list or the address and length of an array of SVs.  The last argument\npoints to a boolean; on return, if that boolean is true, then locale-specific information has\nbeen used to format the string, and the string's contents are therefore untrustworthy (see\nperlsec).  This pointer may be NULL if that information is not important.  Note that this\nfunction requires you to specify the length of the format.\n\nThe \"svset*()\" functions are not generic enough to operate on values that have \"magic\".  See\n\"Magic Virtual Tables\" later in this document.\n\nAll SVs that contain strings should be terminated with a \"NUL\" character.  If it is not\n\"NUL\"-terminated there is a risk of core dumps and corruptions from code which passes the\nstring to C functions or system calls which expect a \"NUL\"-terminated string.  Perl's own\nfunctions typically add a trailing \"NUL\" for this reason.  Nevertheless, you should be very\ncareful when you pass a string stored in an SV to a C function or system call.\n\nTo access the actual value that an SV points to, Perl's API exposes several macros that\ncoerce the actual scalar type into an IV, UV, double, or string:\n\n•   \"SvIV(SV*)\" (\"IV\") and \"SvUV(SV*)\" (\"UV\")\n\n•   \"SvNV(SV*)\" (\"double\")\n\n•   Strings are a bit complicated:\n\n•   Byte string: \"SvPVbyte(SV*, STRLEN len)\" or \"SvPVbytenolen(SV*)\"\n\nIf the Perl string is \"\\xff\\xff\", then this returns a 2-byte \"char*\".\n\nThis is suitable for Perl strings that represent bytes.\n\n•   UTF-8 string: \"SvPVutf8(SV*, STRLEN len)\" or \"SvPVutf8nolen(SV*)\"\n\nIf the Perl string is \"\\xff\\xff\", then this returns a 4-byte \"char*\".\n\nThis is suitable for Perl strings that represent characters.\n\nCAVEAT: That \"char*\" will be encoded via Perl's internal UTF-8 variant, which means\nthat if the SV contains non-Unicode code points (e.g., 0x110000), then the result may\ncontain extensions over valid UTF-8.  See \"isstrictutf8string\" in perlapi for some\nmethods Perl gives you to check the UTF-8 validity of these macros' returns.\n\n•   You can also use \"SvPV(SV*, STRLEN len)\" or \"SvPVnolen(SV*)\" to fetch the SV's raw\ninternal buffer. This is tricky, though; if your Perl string is \"\\xff\\xff\", then\ndepending on the SV's internal encoding you might get back a 2-byte OR a 4-byte\n\"char*\".  Moreover, if it's the 4-byte string, that could come from either Perl\n\"\\xff\\xff\" stored UTF-8 encoded, or Perl \"\\xc3\\xbf\\xc3\\xbf\" stored as raw octets. To\ndifferentiate between these you MUST look up the SV's UTF8 bit (cf. \"SvUTF8\") to know\nwhether the source Perl string is 2 characters (\"SvUTF8\" would be on) or 4 characters\n(\"SvUTF8\" would be off).\n\nIMPORTANT: Use of \"SvPV\", \"SvPVnolen\", or similarly-named macros without looking up\nthe SV's UTF8 bit is almost certainly a bug if non-ASCII input is allowed.\n\nWhen the UTF8 bit is on, the same CAVEAT about UTF-8 validity applies here as for\n\"SvPVutf8\".\n\n(See \"How do I pass a Perl string to a C library?\" for more details.)\n\nIn \"SvPVbyte\", \"SvPVutf8\", and \"SvPV\", the length of the \"char*\" returned is placed into\nthe variable \"len\" (these are macros, so you do not use &len). If you do not care what\nthe length of the data is, use \"SvPVbytenolen\", \"SvPVutf8nolen\", or \"SvPVnolen\"\ninstead.  The global variable \"PLna\" can also be given to \"SvPVbyte\"/\"SvPVutf8\"/\"SvPV\"\nin this case.  But that can be quite inefficient because \"PLna\" must be accessed in\nthread-local storage in threaded Perl.  In any case, remember that Perl allows arbitrary\nstrings of data that may both contain NULs and might not be terminated by a \"NUL\".\n\nAlso remember that C doesn't allow you to safely say \"foo(SvPVbyte(s, len), len);\".  It\nmight work with your compiler, but it won't work for everyone.  Break this sort of\nstatement up into separate assignments:\n\nSV *s;\nSTRLEN len;\nchar *ptr;\nptr = SvPVbyte(s, len);\nfoo(ptr, len);\n\nIf you want to know if the scalar value is TRUE, you can use:\n\nSvTRUE(SV*)\n\nAlthough Perl will automatically grow strings for you, if you need to force Perl to allocate\nmore memory for your SV, you can use the macro\n\nSvGROW(SV*, STRLEN newlen)\n\nwhich will determine if more memory needs to be allocated.  If so, it will call the function\n\"svgrow\".  Note that \"SvGROW\" can only increase, not decrease, the allocated memory of an SV\nand that it does not automatically add space for the trailing \"NUL\" byte (perl's own string\nfunctions typically do \"SvGROW(sv, len + 1)\").\n\nIf you want to write to an existing SV's buffer and set its value to a string, use\nSvPVbyteforce() or one of its variants to force the SV to be a PV.  This will remove any of\nvarious types of non-stringness from the SV while preserving the content of the SV in the PV.\nThis can be used, for example, to append data from an API function to a buffer without extra\ncopying:\n\n(void)SvPVbyteforce(sv, len);\ns = SvGROW(sv, len + needlen + 1);\n/* something that modifies up to needlen bytes at s+len, but\nmodifies newlen bytes\neg. newlen = read(fd, s + len, needlen);\nignoring errors for these examples\n*/\ns[len + newlen] = '\\0';\nSvCURset(sv, len + newlen);\nSvUTF8off(sv);\nSvSETMAGIC(sv);\n\nIf you already have the data in memory or if you want to keep your code simple, you can use\none of the svcat*() variants, such as svcatpvn().  If you want to insert anywhere in the\nstring you can use svinsert() or svinsertflags().\n\nIf you don't need the existing content of the SV, you can avoid some copying with:\n\nSvPVCLEAR(sv);\ns = SvGROW(sv, needlen + 1);\n/* something that modifies up to needlen bytes at s, but modifies\nnewlen bytes\neg. newlen = read(fd, s, needlen);\n*/\ns[newlen] = '\\0';\nSvCURset(sv, newlen);\nSvPOKonly(sv); /* also clears SVfUTF8 */\nSvSETMAGIC(sv);\n\nAgain, if you already have the data in memory or want to avoid the complexity of the above,\nyou can use svsetpvn().\n\nIf you have a buffer allocated with Newx() and want to set that as the SV's value, you can\nuse svusepvnflags().  That has some requirements if you want to avoid perl re-allocating\nthe buffer to fit the trailing NUL:\n\nNewx(buf, somesize+1, char);\n/* ... fill in buf ... */\nbuf[somesize] = '\\0';\nsvusepvnflags(sv, buf, somesize, SVSMAGIC | SVHASTRAILINGNUL);\n/* buf now belongs to perl, don't release it */\n\nIf you have an SV and want to know what kind of data Perl thinks is stored in it, you can use\nthe following macros to check the type of SV you have.\n\nSvIOK(SV*)\nSvNOK(SV*)\nSvPOK(SV*)\n\nYou can get and set the current length of the string stored in an SV with the following\nmacros:\n\nSvCUR(SV*)\nSvCURset(SV*, I32 val)\n\nYou can also get a pointer to the end of the string stored in the SV with the macro:\n\nSvEND(SV*)\n\nBut note that these last three macros are valid only if \"SvPOK()\" is true.\n\nIf you want to append something to the end of string stored in an \"SV*\", you can use the\nfollowing functions:\n\nvoid  svcatpv(SV*, const char*);\nvoid  svcatpvn(SV*, const char*, STRLEN);\nvoid  svcatpvf(SV*, const char*, ...);\nvoid  svvcatpvfn(SV*, const char*, STRLEN, valist *, SV ,\nI32, bool);\nvoid  svcatsv(SV*, SV*);\n\nThe first function calculates the length of the string to be appended by using \"strlen\".  In\nthe second, you specify the length of the string yourself.  The third function processes its\narguments like \"sprintf\" and appends the formatted output.  The fourth function works like\n\"vsprintf\".  You can specify the address and length of an array of SVs instead of the valist\nargument.  The fifth function extends the string stored in the first SV with the string\nstored in the second SV.  It also forces the second SV to be interpreted as a string.\n\nThe \"svcat*()\" functions are not generic enough to operate on values that have \"magic\".  See\n\"Magic Virtual Tables\" later in this document.\n\nIf you know the name of a scalar variable, you can get a pointer to its SV by using the\nfollowing:\n\nSV*  getsv(\"package::varname\", 0);\n\nThis returns NULL if the variable does not exist.\n\nIf you want to know if this variable (or any other SV) is actually \"defined\", you can call:\n\nSvOK(SV*)\n\nThe scalar \"undef\" value is stored in an SV instance called \"PLsvundef\".\n\nIts address can be used whenever an \"SV*\" is needed.  Make sure that you don't try to compare\na random sv with &PLsvundef.  For example when interfacing Perl code, it'll work correctly\nfor:\n\nfoo(undef);\n\nBut won't work when called as:\n\n$x = undef;\nfoo($x);\n\nSo to repeat always use SvOK() to check whether an sv is defined.\n\nAlso you have to be careful when using &PLsvundef as a value in AVs or HVs (see \"AVs, HVs\nand undefined values\").\n\nThere are also the two values \"PLsvyes\" and \"PLsvno\", which contain boolean TRUE and\nFALSE values, respectively.  Like \"PLsvundef\", their addresses can be used whenever an\n\"SV*\" is needed.\n\nDo not be fooled into thinking that \"(SV *) 0\" is the same as &PLsvundef.  Take this code:\n\nSV* sv = (SV*) 0;\nif (I-am-to-return-a-real-value) {\nsv = sv2mortal(newSViv(42));\n}\nsvsetsv(ST(0), sv);\n\nThis code tries to return a new SV (which contains the value 42) if it should return a real\nvalue, or undef otherwise.  Instead it has returned a NULL pointer which, somewhere down the\nline, will cause a segmentation violation, bus error, or just weird results.  Change the zero\nto &PLsvundef in the first line and all will be well.\n\nTo free an SV that you've created, call \"SvREFCNTdec(SV*)\".  Normally this call is not\nnecessary (see \"Reference Counts and Mortality\").\n"
                    },
                    {
                        "name": "Offsets",
                        "content": "Perl provides the function \"svchop\" to efficiently remove characters from the beginning of a\nstring; you give it an SV and a pointer to somewhere inside the PV, and it discards\neverything before the pointer.  The efficiency comes by means of a little hack: instead of\nactually removing the characters, \"svchop\" sets the flag \"OOK\" (offset OK) to signal to\nother functions that the offset hack is in effect, and it moves the PV pointer (called\n\"SvPVX\") forward by the number of bytes chopped off, and adjusts \"SvCUR\" and \"SvLEN\"\naccordingly.  (A portion of the space between the old and new PV pointers is used to store\nthe count of chopped bytes.)\n\nHence, at this point, the start of the buffer that we allocated lives at \"SvPVX(sv) -\nSvIV(sv)\" in memory and the PV pointer is pointing into the middle of this allocated storage.\n\nThis is best demonstrated by example.  Normally copy-on-write will prevent the substitution\nfrom operator from using this hack, but if you can craft a string for which copy-on-write is\nnot possible, you can see it in play.  In the current implementation, the final byte of a\nstring buffer is used as a copy-on-write reference count.  If the buffer is not big enough,\nthen copy-on-write is skipped.  First have a look at an empty string:\n\n% ./perl -Ilib -MDevel::Peek -le '$a=\"\"; $a .= \"\"; Dump $a'\nSV = PV(0x7ffb7c008a70) at 0x7ffb7c030390\nREFCNT = 1\nFLAGS = (POK,pPOK)\nPV = 0x7ffb7bc05b50 \"\"\\0\nCUR = 0\nLEN = 10\n\nNotice here the LEN is 10.  (It may differ on your platform.)  Extend the length of the\nstring to one less than 10, and do a substitution:\n\n% ./perl -Ilib -MDevel::Peek -le '$a=\"\"; $a.=\"123456789\"; $a=~s/.//; \\\nDump($a)'\nSV = PV(0x7ffa04008a70) at 0x7ffa04030390\nREFCNT = 1\nFLAGS = (POK,OOK,pPOK)\nOFFSET = 1\nPV = 0x7ffa03c05b61 ( \"\\1\" . ) \"23456789\"\\0\nCUR = 8\nLEN = 9\n\nHere the number of bytes chopped off (1) is shown next as the OFFSET.  The portion of the\nstring between the \"real\" and the \"fake\" beginnings is shown in parentheses, and the values\nof \"SvCUR\" and \"SvLEN\" reflect the fake beginning, not the real one.  (The first character of\nthe string buffer happens to have changed to \"\\1\" here, not \"1\", because the current\nimplementation stores the offset count in the string buffer.  This is subject to change.)\n\nSomething similar to the offset hack is performed on AVs to enable efficient shifting and\nsplicing off the beginning of the array; while \"AvARRAY\" points to the first element in the\narray that is visible from Perl, \"AvALLOC\" points to the real start of the C array.  These\nare usually the same, but a \"shift\" operation can be carried out by increasing \"AvARRAY\" by\none and decreasing \"AvFILL\" and \"AvMAX\".  Again, the location of the real start of the C\narray only comes into play when freeing the array.  See \"avshift\" in av.c.\n"
                    },
                    {
                        "name": "What's Really Stored in an SV?",
                        "content": "Recall that the usual method of determining the type of scalar you have is to use \"Sv*OK\"\nmacros.  Because a scalar can be both a number and a string, usually these macros will always\nreturn TRUE and calling the \"Sv*V\" macros will do the appropriate conversion of string to\ninteger/double or integer/double to string.\n\nIf you really need to know if you have an integer, double, or string pointer in an SV, you\ncan use the following three macros instead:\n\nSvIOKp(SV*)\nSvNOKp(SV*)\nSvPOKp(SV*)\n\nThese will tell you if you truly have an integer, double, or string pointer stored in your\nSV.  The \"p\" stands for private.\n\nThere are various ways in which the private and public flags may differ.  For example, in\nperl 5.16 and earlier a tied SV may have a valid underlying value in the IV slot (so SvIOKp\nis true), but the data should be accessed via the FETCH routine rather than directly, so\nSvIOK is false.  (In perl 5.18 onwards, tied scalars use the flags the same way as untied\nscalars.)  Another is when numeric conversion has occurred and precision has been lost: only\nthe private flag is set on 'lossy' values.  So when an NV is converted to an IV with loss,\nSvIOKp, SvNOKp and SvNOK will be set, while SvIOK wont be.\n\nIn general, though, it's best to use the \"Sv*V\" macros.\n"
                    },
                    {
                        "name": "Working with AVs",
                        "content": "There are two ways to create and load an AV.  The first method creates an empty AV:\n\nAV*  newAV();\n\nThe second method both creates the AV and initially populates it with SVs:\n\nAV*  avmake(SSizet num, SV ptr);\n\nThe second argument points to an array containing \"num\" \"SV*\"'s.  Once the AV has been\ncreated, the SVs can be destroyed, if so desired.\n\nOnce the AV has been created, the following operations are possible on it:\n\nvoid  avpush(AV*, SV*);\nSV*   avpop(AV*);\nSV*   avshift(AV*);\nvoid  avunshift(AV*, SSizet num);\n\nThese should be familiar operations, with the exception of \"avunshift\".  This routine adds\n\"num\" elements at the front of the array with the \"undef\" value.  You must then use\n\"avstore\" (described below) to assign values to these new elements.\n\nHere are some other functions:\n\nSSizet avtopindex(AV*);\nSV    avfetch(AV*, SSizet key, I32 lval);\nSV    avstore(AV*, SSizet key, SV* val);\n\nThe \"avtopindex\" function returns the highest index value in an array (just like $#array in\nPerl).  If the array is empty, -1 is returned.  The \"avfetch\" function returns the value at\nindex \"key\", but if \"lval\" is non-zero, then \"avfetch\" will store an undef value at that\nindex.  The \"avstore\" function stores the value \"val\" at index \"key\", and does not increment\nthe reference count of \"val\".  Thus the caller is responsible for taking care of that, and if\n\"avstore\" returns NULL, the caller will have to decrement the reference count to avoid a\nmemory leak.  Note that \"avfetch\" and \"avstore\" both return \"SV\"'s, not \"SV*\"'s as their\nreturn value.\n\nA few more:\n\nvoid  avclear(AV*);\nvoid  avundef(AV*);\nvoid  avextend(AV*, SSizet key);\n\nThe \"avclear\" function deletes all the elements in the AV* array, but does not actually\ndelete the array itself.  The \"avundef\" function will delete all the elements in the array\nplus the array itself.  The \"avextend\" function extends the array so that it contains at\nleast \"key+1\" elements.  If \"key+1\" is less than the currently allocated length of the array,\nthen nothing is done.\n\nIf you know the name of an array variable, you can get a pointer to its AV by using the\nfollowing:\n\nAV*  getav(\"package::varname\", 0);\n\nThis returns NULL if the variable does not exist.\n\nSee \"Understanding the Magic of Tied Hashes and Arrays\" for more information on how to use\nthe array access functions on tied arrays.\n"
                    },
                    {
                        "name": "Working with HVs",
                        "content": "To create an HV, you use the following routine:\n\nHV*  newHV();\n\nOnce the HV has been created, the following operations are possible on it:\n\nSV  hvstore(HV*, const char* key, U32 klen, SV* val, U32 hash);\nSV  hvfetch(HV*, const char* key, U32 klen, I32 lval);\n\nThe \"klen\" parameter is the length of the key being passed in (Note that you cannot pass 0 in\nas a value of \"klen\" to tell Perl to measure the length of the key).  The \"val\" argument\ncontains the SV pointer to the scalar being stored, and \"hash\" is the precomputed hash value\n(zero if you want \"hvstore\" to calculate it for you).  The \"lval\" parameter indicates\nwhether this fetch is actually a part of a store operation, in which case a new undefined\nvalue will be added to the HV with the supplied key and \"hvfetch\" will return as if the\nvalue had already existed.\n\nRemember that \"hvstore\" and \"hvfetch\" return \"SV\"'s and not just \"SV*\".  To access the\nscalar value, you must first dereference the return value.  However, you should check to make\nsure that the return value is not NULL before dereferencing it.\n\nThe first of these two functions checks if a hash table entry exists, and the second deletes\nit.\n\nbool  hvexists(HV*, const char* key, U32 klen);\nSV*   hvdelete(HV*, const char* key, U32 klen, I32 flags);\n\nIf \"flags\" does not include the \"GDISCARD\" flag then \"hvdelete\" will create and return a\nmortal copy of the deleted value.\n\nAnd more miscellaneous functions:\n\nvoid   hvclear(HV*);\nvoid   hvundef(HV*);\n\nLike their AV counterparts, \"hvclear\" deletes all the entries in the hash table but does not\nactually delete the hash table.  The \"hvundef\" deletes both the entries and the hash table\nitself.\n\nPerl keeps the actual data in a linked list of structures with a typedef of HE.  These\ncontain the actual key and value pointers (plus extra administrative overhead).  The key is a\nstring pointer; the value is an \"SV*\".  However, once you have an \"HE*\", to get the actual\nkey and value, use the routines specified below.\n\nI32    hviterinit(HV*);\n/* Prepares starting point to traverse hash table */\nHE*    hviternext(HV*);\n/* Get the next entry, and return a pointer to a\nstructure that has both the key and value */\nchar*  hviterkey(HE* entry, I32* retlen);\n/* Get the key from an HE structure and also return\nthe length of the key string */\nSV*    hviterval(HV*, HE* entry);\n/* Return an SV pointer to the value of the HE\nstructure */\nSV*    hviternextsv(HV*, char key, I32* retlen);\n/* This convenience routine combines hviternext,\nhviterkey, and hviterval.  The key and retlen\narguments are return values for the key and its\nlength.  The value is returned in the SV* argument */\n\nIf you know the name of a hash variable, you can get a pointer to its HV by using the\nfollowing:\n\nHV*  gethv(\"package::varname\", 0);\n\nThis returns NULL if the variable does not exist.\n\nThe hash algorithm is defined in the \"PERLHASH\" macro:\n\nPERLHASH(hash, key, klen)\n\nThe exact implementation of this macro varies by architecture and version of perl, and the\nreturn value may change per invocation, so the value is only valid for the duration of a\nsingle perl process.\n\nSee \"Understanding the Magic of Tied Hashes and Arrays\" for more information on how to use\nthe hash access functions on tied hashes.\n"
                    },
                    {
                        "name": "Hash API Extensions",
                        "content": "Beginning with version 5.004, the following functions are also supported:\n\nHE*     hvfetchent  (HV* tb, SV* key, I32 lval, U32 hash);\nHE*     hvstoreent  (HV* tb, SV* key, SV* val, U32 hash);\n\nbool    hvexistsent (HV* tb, SV* key, U32 hash);\nSV*     hvdeleteent (HV* tb, SV* key, I32 flags, U32 hash);\n\nSV*     hviterkeysv  (HE* entry);\n\nNote that these functions take \"SV*\" keys, which simplifies writing of extension code that\ndeals with hash structures.  These functions also allow passing of \"SV*\" keys to \"tie\"\nfunctions without forcing you to stringify the keys (unlike the previous set of functions).\n\nThey also return and accept whole hash entries (\"HE*\"), making their use more efficient\n(since the hash number for a particular string doesn't have to be recomputed every time).\nSee perlapi for detailed descriptions.\n\nThe following macros must always be used to access the contents of hash entries.  Note that\nthe arguments to these macros must be simple variables, since they may get evaluated more\nthan once.  See perlapi for detailed descriptions of these macros.\n\nHePV(HE* he, STRLEN len)\nHeVAL(HE* he)\nHeHASH(HE* he)\nHeSVKEY(HE* he)\nHeSVKEYforce(HE* he)\nHeSVKEYset(HE* he, SV* sv)\n\nThese two lower level macros are defined, but must only be used when dealing with keys that\nare not \"SV*\"s:\n\nHeKEY(HE* he)\nHeKLEN(HE* he)\n\nNote that both \"hvstore\" and \"hvstoreent\" do not increment the reference count of the\nstored \"val\", which is the caller's responsibility.  If these functions return a NULL value,\nthe caller will usually have to decrement the reference count of \"val\" to avoid a memory\nleak.\n"
                    },
                    {
                        "name": "AVs, HVs and undefined values",
                        "content": "Sometimes you have to store undefined values in AVs or HVs.  Although this may be a rare\ncase, it can be tricky.  That's because you're used to using &PLsvundef if you need an\nundefined SV.\n\nFor example, intuition tells you that this XS code:\n\nAV *av = newAV();\navstore( av, 0, &PLsvundef );\n\nis equivalent to this Perl code:\n\nmy @av;\n$av[0] = undef;\n\nUnfortunately, this isn't true.  In perl 5.18 and earlier, AVs use &PLsvundef as a marker\nfor indicating that an array element has not yet been initialized.  Thus, \"exists $av[0]\"\nwould be true for the above Perl code, but false for the array generated by the XS code.  In\nperl 5.20, storing &PLsvundef will create a read-only element, because the scalar\n&PLsvundef itself is stored, not a copy.\n\nSimilar problems can occur when storing &PLsvundef in HVs:\n\nhvstore( hv, \"key\", 3, &PLsvundef, 0 );\n\nThis will indeed make the value \"undef\", but if you try to modify the value of \"key\", you'll\nget the following error:\n\nModification of non-creatable hash value attempted\n\nIn perl 5.8.0, &PLsvundef was also used to mark placeholders in restricted hashes.  This\ncaused such hash entries not to appear when iterating over the hash or when checking for the\nkeys with the \"hvexists\" function.\n\nYou can run into similar problems when you store &PLsvyes or &PLsvno into AVs or HVs.\nTrying to modify such elements will give you the following error:\n\nModification of a read-only value attempted\n\nTo make a long story short, you can use the special variables &PLsvundef, &PLsvyes and\n&PLsvno with AVs and HVs, but you have to make sure you know what you're doing.\n\nGenerally, if you want to store an undefined value in an AV or HV, you should not use\n&PLsvundef, but rather create a new undefined value using the \"newSV\" function, for\nexample:\n\navstore( av, 42, newSV(0) );\nhvstore( hv, \"foo\", 3, newSV(0), 0 );\n"
                    },
                    {
                        "name": "References",
                        "content": "References are a special type of scalar that point to other data types (including other\nreferences).\n\nTo create a reference, use either of the following functions:\n\nSV* newRVinc((SV*) thing);\nSV* newRVnoinc((SV*) thing);\n\nThe \"thing\" argument can be any of an \"SV*\", \"AV*\", or \"HV*\".  The functions are identical\nexcept that \"newRVinc\" increments the reference count of the \"thing\", while \"newRVnoinc\"\ndoes not.  For historical reasons, \"newRV\" is a synonym for \"newRVinc\".\n\nOnce you have a reference, you can use the following macro to dereference the reference:\n\nSvRV(SV*)\n\nthen call the appropriate routines, casting the returned \"SV*\" to either an \"AV*\" or \"HV*\",\nif required.\n\nTo determine if an SV is a reference, you can use the following macro:\n\nSvROK(SV*)\n\nTo discover what type of value the reference refers to, use the following macro and then\ncheck the return value.\n\nSvTYPE(SvRV(SV*))\n\nThe most useful types that will be returned are:\n\nSVtPVAV    Array\nSVtPVHV    Hash\nSVtPVCV    Code\nSVtPVGV    Glob (possibly a file handle)\n\nAny numerical value returned which is less than SVtPVAV will be a scalar of some form.\n\nSee \"svtype\" in perlapi for more details.\n"
                    },
                    {
                        "name": "Blessed References and Class Objects",
                        "content": "References are also used to support object-oriented programming.  In perl's OO lexicon, an\nobject is simply a reference that has been blessed into a package (or class).  Once blessed,\nthe programmer may now use the reference to access the various methods in the class.\n\nA reference can be blessed into a package with the following function:\n\nSV* svbless(SV* sv, HV* stash);\n\nThe \"sv\" argument must be a reference value.  The \"stash\" argument specifies which class the\nreference will belong to.  See \"Stashes and Globs\" for information on converting class names\ninto stashes.\n\n/* Still under construction */\n\nThe following function upgrades rv to reference if not already one.  Creates a new SV for rv\nto point to.  If \"classname\" is non-null, the SV is blessed into the specified class.  SV is\nreturned.\n\nSV* newSVrv(SV* rv, const char* classname);\n\nThe following three functions copy integer, unsigned integer or double into an SV whose\nreference is \"rv\".  SV is blessed if \"classname\" is non-null.\n\nSV* svsetrefiv(SV* rv, const char* classname, IV iv);\nSV* svsetrefuv(SV* rv, const char* classname, UV uv);\nSV* svsetrefnv(SV* rv, const char* classname, NV iv);\n\nThe following function copies the pointer value (the address, not the string!) into an SV\nwhose reference is rv.  SV is blessed if \"classname\" is non-null.\n\nSV* svsetrefpv(SV* rv, const char* classname, void* pv);\n\nThe following function copies a string into an SV whose reference is \"rv\".  Set length to 0\nto let Perl calculate the string length.  SV is blessed if \"classname\" is non-null.\n\nSV* svsetrefpvn(SV* rv, const char* classname, char* pv,\nSTRLEN length);\n\nThe following function tests whether the SV is blessed into the specified class.  It does not\ncheck inheritance relationships.\n\nint  svisa(SV* sv, const char* name);\n\nThe following function tests whether the SV is a reference to a blessed object.\n\nint  svisobject(SV* sv);\n\nThe following function tests whether the SV is derived from the specified class.  SV can be\neither a reference to a blessed object or a string containing a class name.  This is the\nfunction implementing the \"UNIVERSAL::isa\" functionality.\n\nbool svderivedfrom(SV* sv, const char* name);\n\nTo check if you've got an object derived from a specific class you have to write:\n\nif (svisobject(sv) && svderivedfrom(sv, class)) { ... }\n"
                    },
                    {
                        "name": "Creating New Variables",
                        "content": "To create a new Perl variable with an undef value which can be accessed from your Perl\nscript, use the following routines, depending on the variable type.\n\nSV*  getsv(\"package::varname\", GVADD);\nAV*  getav(\"package::varname\", GVADD);\nHV*  gethv(\"package::varname\", GVADD);\n\nNotice the use of GVADD as the second parameter.  The new variable can now be set, using the\nroutines appropriate to the data type.\n\nThere are additional macros whose values may be bitwise OR'ed with the \"GVADD\" argument to\nenable certain extra features.  Those bits are:\n\nGVADDMULTI\nMarks the variable as multiply defined, thus preventing the:\n\nName <varname> used only once: possible typo\n\nwarning.\n\nGVADDWARN\nIssues the warning:\n\nHad to create <varname> unexpectedly\n\nif the variable did not exist before the function was called.\n\nIf you do not specify a package name, the variable is created in the current package.\n"
                    },
                    {
                        "name": "Reference Counts and Mortality",
                        "content": "Perl uses a reference count-driven garbage collection mechanism.  SVs, AVs, or HVs (xV for\nshort in the following) start their life with a reference count of 1.  If the reference count\nof an xV ever drops to 0, then it will be destroyed and its memory made available for reuse.\nAt the most basic internal level, reference counts can be manipulated with the following\nmacros:\n\nint SvREFCNT(SV* sv);\nSV* SvREFCNTinc(SV* sv);\nvoid SvREFCNTdec(SV* sv);\n\n(There are also suffixed versions of the increment and decrement macros, for situations where\nthe full generality of these basic macros can be exchanged for some performance.)\n\nHowever, the way a programmer should think about references is not so much in terms of the\nbare reference count, but in terms of ownership of references.  A reference to an xV can be\nowned by any of a variety of entities: another xV, the Perl interpreter, an XS data\nstructure, a piece of running code, or a dynamic scope.  An xV generally does not know what\nentities own the references to it; it only knows how many references there are, which is the\nreference count.\n\nTo correctly maintain reference counts, it is essential to keep track of what references the\nXS code is manipulating.  The programmer should always know where a reference has come from\nand who owns it, and be aware of any creation or destruction of references, and any transfers\nof ownership.  Because ownership isn't represented explicitly in the xV data structures, only\nthe reference count need be actually maintained by the code, and that means that this\nunderstanding of ownership is not actually evident in the code.  For example, transferring\nownership of a reference from one owner to another doesn't change the reference count at all,\nso may be achieved with no actual code.  (The transferring code doesn't touch the referenced\nobject, but does need to ensure that the former owner knows that it no longer owns the\nreference, and that the new owner knows that it now does.)\n\nAn xV that is visible at the Perl level should not become unreferenced and thus be destroyed.\nNormally, an object will only become unreferenced when it is no longer visible, often by the\nsame means that makes it invisible.  For example, a Perl reference value (RV) owns a\nreference to its referent, so if the RV is overwritten that reference gets destroyed, and the\nno-longer-reachable referent may be destroyed as a result.\n\nMany functions have some kind of reference manipulation as part of their purpose.  Sometimes\nthis is documented in terms of ownership of references, and sometimes it is (less helpfully)\ndocumented in terms of changes to reference counts.  For example, the newRVinc() function is\ndocumented to create a new RV (with reference count 1) and increment the reference count of\nthe referent that was supplied by the caller.  This is best understood as creating a new\nreference to the referent, which is owned by the created RV, and returning to the caller\nownership of the sole reference to the RV.  The newRVnoinc() function instead does not\nincrement the reference count of the referent, but the RV nevertheless ends up owning a\nreference to the referent.  It is therefore implied that the caller of \"newRVnoinc()\" is\nrelinquishing a reference to the referent, making this conceptually a more complicated\noperation even though it does less to the data structures.\n\nFor example, imagine you want to return a reference from an XSUB function.  Inside the XSUB\nroutine, you create an SV which initially has just a single reference, owned by the XSUB\nroutine.  This reference needs to be disposed of before the routine is complete, otherwise it\nwill leak, preventing the SV from ever being destroyed.  So to create an RV referencing the\nSV, it is most convenient to pass the SV to \"newRVnoinc()\", which consumes that reference.\nNow the XSUB routine no longer owns a reference to the SV, but does own a reference to the\nRV, which in turn owns a reference to the SV.  The ownership of the reference to the RV is\nthen transferred by the process of returning the RV from the XSUB.\n\nThere are some convenience functions available that can help with the destruction of xVs.\nThese functions introduce the concept of \"mortality\".  Much documentation speaks of an xV\nitself being mortal, but this is misleading.  It is really a reference to an xV that is\nmortal, and it is possible for there to be more than one mortal reference to a single xV.\nFor a reference to be mortal means that it is owned by the temps stack, one of perl's many\ninternal stacks, which will destroy that reference \"a short time later\".  Usually the \"short\ntime later\" is the end of the current Perl statement.  However, it gets more complicated\naround dynamic scopes: there can be multiple sets of mortal references hanging around at the\nsame time, with different death dates.  Internally, the actual determinant for when mortal xV\nreferences are destroyed depends on two macros, SAVETMPS and FREETMPS.  See perlcall and\nperlxs and \"Temporaries Stack\" below for more details on these macros.\n\nMortal references are mainly used for xVs that are placed on perl's main stack.  The stack is\nproblematic for reference tracking, because it contains a lot of xV references, but doesn't\nown those references: they are not counted.  Currently, there are many bugs resulting from\nxVs being destroyed while referenced by the stack, because the stack's uncounted references\naren't enough to keep the xVs alive.  So when putting an (uncounted) reference on the stack,\nit is vitally important to ensure that there will be a counted reference to the same xV that\nwill last at least as long as the uncounted reference.  But it's also important that that\ncounted reference be cleaned up at an appropriate time, and not unduly prolong the xV's life.\nFor there to be a mortal reference is often the best way to satisfy this requirement,\nespecially if the xV was created especially to be put on the stack and would otherwise be\nunreferenced.\n\nTo create a mortal reference, use the functions:\n\nSV*  svnewmortal()\nSV*  svmortalcopy(SV*)\nSV*  sv2mortal(SV*)\n\n\"svnewmortal()\" creates an SV (with the undefined value) whose sole reference is mortal.\n\"svmortalcopy()\" creates an xV whose value is a copy of a supplied xV and whose sole\nreference is mortal.  \"sv2mortal()\" mortalises an existing xV reference: it transfers\nownership of a reference from the caller to the temps stack.  Because \"svnewmortal\" gives\nthe new SV no value, it must normally be given one via \"svsetpv\", \"svsetiv\", etc. :\n\nSV *tmp = svnewmortal();\nsvsetiv(tmp, aninteger);\n\nAs that is multiple C statements it is quite common so see this idiom instead:\n\nSV *tmp = sv2mortal(newSViv(aninteger));\n\nThe mortal routines are not just for SVs; AVs and HVs can be made mortal by passing their\naddress (type-casted to \"SV*\") to the \"sv2mortal\" or \"svmortalcopy\" routines.\n"
                    },
                    {
                        "name": "Stashes and Globs",
                        "content": "A stash is a hash that contains all variables that are defined within a package.  Each key of\nthe stash is a symbol name (shared by all the different types of objects that have the same\nname), and each value in the hash table is a GV (Glob Value).  This GV in turn contains\nreferences to the various objects of that name, including (but not limited to) the following:\n\nScalar Value\nArray Value\nHash Value\nI/O Handle\nFormat\nSubroutine\n\nThere is a single stash called \"PLdefstash\" that holds the items that exist in the \"main\"\npackage.  To get at the items in other packages, append the string \"::\" to the package name.\nThe items in the \"Foo\" package are in the stash \"Foo::\" in PLdefstash.  The items in the\n\"Bar::Baz\" package are in the stash \"Baz::\" in \"Bar::\"'s stash.\n\nTo get the stash pointer for a particular package, use the function:\n\nHV*  gvstashpv(const char* name, I32 flags)\nHV*  gvstashsv(SV*, I32 flags)\n\nThe first function takes a literal string, the second uses the string stored in the SV.\nRemember that a stash is just a hash table, so you get back an \"HV*\".  The \"flags\" flag will\ncreate a new package if it is set to GVADD.\n\nThe name that \"gvstash*v\" wants is the name of the package whose symbol table you want.  The\ndefault package is called \"main\".  If you have multiply nested packages, pass their names to\n\"gvstash*v\", separated by \"::\" as in the Perl language itself.\n\nAlternately, if you have an SV that is a blessed reference, you can find out the stash\npointer by using:\n\nHV*  SvSTASH(SvRV(SV*));\n\nthen use the following to get the package name itself:\n\nchar*  HvNAME(HV* stash);\n\nIf you need to bless or re-bless an object you can use the following function:\n\nSV*  svbless(SV*, HV* stash)\n\nwhere the first argument, an \"SV*\", must be a reference, and the second argument is a stash.\nThe returned \"SV*\" can now be used in the same way as any other SV.\n\nFor more information on references and blessings, consult perlref.\n"
                    },
                    {
                        "name": "I/O Handles",
                        "content": "Like AVs and HVs, IO objects are another type of non-scalar SV which may contain input and\noutput PerlIO objects or a \"DIR *\" from opendir().\n\nYou can create a new IO object:\n\nIO*  newIO();\n\nUnlike other SVs, a new IO object is automatically blessed into the IO::File class.\n\nThe IO object contains an input and output PerlIO handle:\n\nPerlIO *IoIFP(IO *io);\nPerlIO *IoOFP(IO *io);\n\nTypically if the IO object has been opened on a file, the input handle is always present, but\nthe output handle is only present if the file is open for output.  For a file, if both are\npresent they will be the same PerlIO object.\n\nDistinct input and output PerlIO objects are created for sockets and character devices.\n\nThe IO object also contains other data associated with Perl I/O handles:\n\nIV IoLINES(io);                /* $. */\nIV IoPAGE(io);                 /* $% */\nIV IoPAGELEN(io);             /* $= */\nIV IoLINESLEFT(io);           /* $- */\nchar *IoTOPNAME(io);          /* $^ */\nGV *IoTOPGV(io);              /* $^ */\nchar *IoFMTNAME(io);          /* $~ */\nGV *IoFMTGV(io);              /* $~ */\nchar *IoBOTTOMNAME(io);\nGV *IoBOTTOMGV(io);\nchar IoTYPE(io);\nU8 IoFLAGS(io);\n\nMost of these are involved with formats.\n\nIoFLAGs() may contain a combination of flags, the most interesting of which are \"IOfFLUSH\"\n($|) for autoflush and \"IOfUNTAINT\", settable with IO::Handle's untaint() method.\n\nThe IO object may also contains a directory handle:\n\nDIR *IoDIRP(io);\n\nsuitable for use with PerlDirread() etc.\n\nAll of these accessors macros are lvalues, there are no distinct \"set()\" macros to modify\nthe members of the IO object.\n"
                    },
                    {
                        "name": "Double-Typed SVs",
                        "content": "Scalar variables normally contain only one type of value, an integer, double, pointer, or\nreference.  Perl will automatically convert the actual scalar data from the stored type into\nthe requested type.\n\nSome scalar variables contain more than one type of scalar data.  For example, the variable\n$! contains either the numeric value of \"errno\" or its string equivalent from either\n\"strerror\" or \"syserrlist[]\".\n\nTo force multiple data values into an SV, you must do two things: use the \"svset*v\" routines\nto add the additional scalar type, then set a flag so that Perl will believe it contains more\nthan one type of data.  The four macros to set the flags are:\n\nSvIOKon\nSvNOKon\nSvPOKon\nSvROKon\n\nThe particular macro you must use depends on which \"svset*v\" routine you called first.  This\nis because every \"svset*v\" routine turns on only the bit for the particular type of data\nbeing set, and turns off all the rest.\n\nFor example, to create a new Perl variable called \"dberror\" that contains both the numeric\nand descriptive string error values, you could use the following code:\n\nextern int  dberror;\nextern char *dberrorlist;\n\nSV* sv = getsv(\"dberror\", GVADD);\nsvsetiv(sv, (IV) dberror);\nsvsetpv(sv, dberrorlist[dberror]);\nSvIOKon(sv);\n\nIf the order of \"svsetiv\" and \"svsetpv\" had been reversed, then the macro \"SvPOKon\" would\nneed to be called instead of \"SvIOKon\".\n"
                    },
                    {
                        "name": "Read-Only Values",
                        "content": "In Perl 5.16 and earlier, copy-on-write (see the next section) shared a flag bit with read-\nonly scalars.  So the only way to test whether \"svsetsv\", etc., will raise a \"Modification\nof a read-only value\" error in those versions is:\n\nSvREADONLY(sv) && !SvIsCOW(sv)\n\nUnder Perl 5.18 and later, SvREADONLY only applies to read-only variables, and, under 5.20,\ncopy-on-write scalars can also be read-only, so the above check is incorrect.  You just want:\n\nSvREADONLY(sv)\n\nIf you need to do this check often, define your own macro like this:\n\n#if PERLVERSION >= 18\n# define SvTRULYREADONLY(sv) SvREADONLY(sv)\n#else\n# define SvTRULYREADONLY(sv) (SvREADONLY(sv) && !SvIsCOW(sv))\n#endif\n"
                    },
                    {
                        "name": "Copy on Write",
                        "content": "Perl implements a copy-on-write (COW) mechanism for scalars, in which string copies are not\nimmediately made when requested, but are deferred until made necessary by one or the other\nscalar changing.  This is mostly transparent, but one must take care not to modify string\nbuffers that are shared by multiple SVs.\n\nYou can test whether an SV is using copy-on-write with \"SvIsCOW(sv)\".\n\nYou can force an SV to make its own copy of its string buffer by calling\n\"svforcenormal(sv)\" or SvPVforcenolen(sv).\n\nIf you want to make the SV drop its string buffer, use \"svforcenormalflags(sv,\nSVCOWDROPPV)\" or simply \"svsetsv(sv, NULL)\".\n\nAll of these functions will croak on read-only scalars (see the previous section for more on\nthose).\n\nTo test that your code is behaving correctly and not modifying COW buffers, on systems that\nsupport mmap(2) (i.e., Unix) you can configure perl with\n\"-Accflags=-DPERLDEBUGREADONLYCOW\" and it will turn buffer violations into crashes.  You\nwill find it to be marvellously slow, so you may want to skip perl's own tests.\n"
                    },
                    {
                        "name": "Magic Variables",
                        "content": "[This section still under construction.  Ignore everything here.  Post no bills.  Everything\nnot permitted is forbidden.]\n\nAny SV may be magical, that is, it has special features that a normal SV does not have.\nThese features are stored in the SV structure in a linked list of \"struct magic\"'s,\ntypedef'ed to \"MAGIC\".\n\nstruct magic {\nMAGIC*      mgmoremagic;\nMGVTBL*     mgvirtual;\nU16         mgprivate;\nchar        mgtype;\nU8          mgflags;\nI32         mglen;\nSV*         mgobj;\nchar*       mgptr;\n};\n\nNote this is current as of patchlevel 0, and could change at any time.\n"
                    },
                    {
                        "name": "Assigning Magic",
                        "content": "Perl adds magic to an SV using the svmagic function:\n\nvoid svmagic(SV* sv, SV* obj, int how, const char* name, I32 namlen);\n\nThe \"sv\" argument is a pointer to the SV that is to acquire a new magical feature.\n\nIf \"sv\" is not already magical, Perl uses the \"SvUPGRADE\" macro to convert \"sv\" to type\n\"SVtPVMG\".  Perl then continues by adding new magic to the beginning of the linked list of\nmagical features.  Any prior entry of the same type of magic is deleted.  Note that this can\nbe overridden, and multiple instances of the same type of magic can be associated with an SV.\n\nThe \"name\" and \"namlen\" arguments are used to associate a string with the magic, typically\nthe name of a variable.  \"namlen\" is stored in the \"mglen\" field and if \"name\" is non-null\nthen either a \"savepvn\" copy of \"name\" or \"name\" itself is stored in the \"mgptr\" field,\ndepending on whether \"namlen\" is greater than zero or equal to zero respectively.  As a\nspecial case, if \"(name && namlen == HEfSVKEY)\" then \"name\" is assumed to contain an \"SV*\"\nand is stored as-is with its REFCNT incremented.\n\nThe svmagic function uses \"how\" to determine which, if any, predefined \"Magic Virtual Table\"\nshould be assigned to the \"mgvirtual\" field.  See the \"Magic Virtual Tables\" section below.\nThe \"how\" argument is also stored in the \"mgtype\" field.  The value of \"how\" should be\nchosen from the set of macros \"PERLMAGICfoo\" found in perl.h.  Note that before these\nmacros were added, Perl internals used to directly use character literals, so you may\noccasionally come across old code or documentation referring to 'U' magic rather than\n\"PERLMAGICuvar\" for example.\n\nThe \"obj\" argument is stored in the \"mgobj\" field of the \"MAGIC\" structure.  If it is not\nthe same as the \"sv\" argument, the reference count of the \"obj\" object is incremented.  If it\nis the same, or if the \"how\" argument is \"PERLMAGICarylen\", \"PERLMAGICregdatum\",\n\"PERLMAGICregdata\", or if it is a NULL pointer, then \"obj\" is merely stored, without the\nreference count being incremented.\n\nSee also \"svmagicext\" in perlapi for a more flexible way to add magic to an SV.\n\nThere is also a function to add magic to an \"HV\":\n\nvoid hvmagic(HV *hv, GV *gv, int how);\n\nThis simply calls \"svmagic\" and coerces the \"gv\" argument into an \"SV\".\n\nTo remove the magic from an SV, call the function svunmagic:\n\nint svunmagic(SV *sv, int type);\n\nThe \"type\" argument should be equal to the \"how\" value when the \"SV\" was initially made\nmagical.\n\nHowever, note that \"svunmagic\" removes all magic of a certain \"type\" from the \"SV\".  If you\nwant to remove only certain magic of a \"type\" based on the magic virtual table, use\n\"svunmagicext\" instead:\n\nint svunmagicext(SV *sv, int type, MGVTBL *vtbl);\n"
                    },
                    {
                        "name": "Magic Virtual Tables",
                        "content": "The \"mgvirtual\" field in the \"MAGIC\" structure is a pointer to an \"MGVTBL\", which is a\nstructure of function pointers and stands for \"Magic Virtual Table\" to handle the various\noperations that might be applied to that variable.\n\nThe \"MGVTBL\" has five (or sometimes eight) pointers to the following routine types:\n\nint  (*svtget)  (pTHX SV* sv, MAGIC* mg);\nint  (*svtset)  (pTHX SV* sv, MAGIC* mg);\nU32  (*svtlen)  (pTHX SV* sv, MAGIC* mg);\nint  (*svtclear)(pTHX SV* sv, MAGIC* mg);\nint  (*svtfree) (pTHX SV* sv, MAGIC* mg);\n\nint  (*svtcopy) (pTHX SV *sv, MAGIC* mg, SV *nsv,\nconst char *name, I32 namlen);\nint  (*svtdup)  (pTHX MAGIC *mg, CLONEPARAMS *param);\nint  (*svtlocal)(pTHX SV *nsv, MAGIC *mg);\n\nThis MGVTBL structure is set at compile-time in perl.h and there are currently 32 types.\nThese different structures contain pointers to various routines that perform additional\nactions depending on which function is being called.\n\nFunction pointer    Action taken\n----------------    ------------\nsvtget             Do something before the value of the SV is\nretrieved.\nsvtset             Do something after the SV is assigned a value.\nsvtlen             Report on the SV's length.\nsvtclear           Clear something the SV represents.\nsvtfree            Free any extra storage associated with the SV.\n\nsvtcopy            copy tied variable magic to a tied element\nsvtdup             duplicate a magic structure during thread cloning\nsvtlocal           copy magic to local value during 'local'\n\nFor instance, the MGVTBL structure called \"vtblsv\" (which corresponds to an \"mgtype\" of\n\"PERLMAGICsv\") contains:\n\n{ magicget, magicset, magiclen, 0, 0 }\n\nThus, when an SV is determined to be magical and of type \"PERLMAGICsv\", if a get operation\nis being performed, the routine \"magicget\" is called.  All the various routines for the\nvarious magical types begin with \"magic\".  NOTE: the magic routines are not considered part\nof the Perl API, and may not be exported by the Perl library.\n\nThe last three slots are a recent addition, and for source code compatibility they are only\nchecked for if one of the three flags MGfCOPY, MGfDUP or MGfLOCAL is set in mgflags.\nThis means that most code can continue declaring a vtable as a 5-element value.  These three\nare currently used exclusively by the threading code, and are highly subject to change.\n\nThe current kinds of Magic Virtual Tables are:\n\nmgtype\n(old-style char and macro)   MGVTBL         Type of magic\n--------------------------   ------         -------------\n\\0 PERLMAGICsv             vtblsv        Special scalar variable\n#  PERLMAGICarylen         vtblarylen    Array length ($#ary)\n%  PERLMAGICrhash          (none)         Extra data for restricted\nhashes\n*  PERLMAGICdebugvar       vtbldebugvar  $DB::single, signal, trace\nvars\n.  PERLMAGICpos            vtblpos       pos() lvalue\n:  PERLMAGICsymtab         (none)         Extra data for symbol\ntables\n<  PERLMAGICbackref        vtblbackref   For weak ref data\n@  PERLMAGICarylenp       (none)         To move arylen out of XPVAV\nB  PERLMAGICbm             vtblregexp    Boyer-Moore\n(fast string search)\nc  PERLMAGICoverloadtable vtblovrld     Holds overload table\n(AMT) on stash\nD  PERLMAGICregdata        vtblregdata   Regex match position data\n(@+ and @- vars)\nd  PERLMAGICregdatum       vtblregdatum  Regex match position data\nelement\nE  PERLMAGICenv            vtblenv       %ENV hash\ne  PERLMAGICenvelem        vtblenvelem   %ENV hash element\nf  PERLMAGICfm             vtblregexp    Formline\n('compiled' format)\ng  PERLMAGICregexglobal   vtblmglob     m//g target\nH  PERLMAGIChints          vtblhints     %^H hash\nh  PERLMAGIChintselem      vtblhintselem %^H hash element\nI  PERLMAGICisa            vtblisa       @ISA array\ni  PERLMAGICisaelem        vtblisaelem   @ISA array element\nk  PERLMAGICnkeys          vtblnkeys     scalar(keys()) lvalue\nL  PERLMAGICdbfile         (none)         Debugger %<filename\nl  PERLMAGICdbline         vtbldbline    Debugger %<filename\nelement\nN  PERLMAGICshared         (none)         Shared between threads\nn  PERLMAGICsharedscalar  (none)         Shared between threads\no  PERLMAGICcollxfrm       vtblcollxfrm  Locale transformation\nP  PERLMAGICtied           vtblpack      Tied array or hash\np  PERLMAGICtiedelem       vtblpackelem  Tied array or hash element\nq  PERLMAGICtiedscalar     vtblpackelem  Tied scalar or handle\nr  PERLMAGICqr             vtblregexp    Precompiled qr// regex\nS  PERLMAGICsig            (none)         %SIG hash\ns  PERLMAGICsigelem        vtblsigelem   %SIG hash element\nt  PERLMAGICtaint          vtbltaint     Taintedness\nU  PERLMAGICuvar           vtbluvar      Available for use by\nextensions\nu  PERLMAGICuvarelem      (none)         Reserved for use by\nextensions\nV  PERLMAGICvstring        (none)         SV was vstring literal\nv  PERLMAGICvec            vtblvec       vec() lvalue\nw  PERLMAGICutf8           vtblutf8      Cached UTF-8 information\nx  PERLMAGICsubstr         vtblsubstr    substr() lvalue\nY  PERLMAGICnonelem        vtblnonelem   Array element that does not\nexist\ny  PERLMAGICdefelem        vtbldefelem   Shadow \"foreach\" iterator\nvariable / smart parameter\nvivification\n\\  PERLMAGIClvref          vtbllvref     Lvalue reference\nconstructor\n]  PERLMAGICcheckcall      vtblcheckcall Inlining/mutation of call\nto this CV\n~  PERLMAGICext            (none)         Available for use by\nextensions\n\nWhen an uppercase and lowercase letter both exist in the table, then the uppercase letter is\ntypically used to represent some kind of composite type (a list or a hash), and the lowercase\nletter is used to represent an element of that composite type.  Some internals code makes use\nof this case relationship.  However, 'v' and 'V' (vec and v-string) are in no way related.\n\nThe \"PERLMAGICext\" and \"PERLMAGICuvar\" magic types are defined specifically for use by\nextensions and will not be used by perl itself.  Extensions can use \"PERLMAGICext\" magic to\n'attach' private information to variables (typically objects).  This is especially useful\nbecause there is no way for normal perl code to corrupt this private information (unlike\nusing extra elements of a hash object).\n\nSimilarly, \"PERLMAGICuvar\" magic can be used much like tie() to call a C function any time\na scalar's value is used or changed.  The \"MAGIC\"'s \"mgptr\" field points to a \"ufuncs\"\nstructure:\n\nstruct ufuncs {\nI32 (*ufval)(pTHX IV, SV*);\nI32 (*ufset)(pTHX IV, SV*);\nIV ufindex;\n};\n\nWhen the SV is read from or written to, the \"ufval\" or \"ufset\" function will be called with\n\"ufindex\" as the first arg and a pointer to the SV as the second.  A simple example of how\nto add \"PERLMAGICuvar\" magic is shown below.  Note that the ufuncs structure is copied by\nsvmagic, so you can safely allocate it on the stack.\n\nvoid\nUmagic(sv)\nSV *sv;\nPREINIT:\nstruct ufuncs uf;\nCODE:\nuf.ufval   = &mygetfn;\nuf.ufset   = &mysetfn;\nuf.ufindex = 0;\nsvmagic(sv, 0, PERLMAGICuvar, (char*)&uf, sizeof(uf));\n\nAttaching \"PERLMAGICuvar\" to arrays is permissible but has no effect.\n\nFor hashes there is a specialized hook that gives control over hash keys (but not values).\nThis hook calls \"PERLMAGICuvar\" 'get' magic if the \"set\" function in the \"ufuncs\" structure\nis NULL.  The hook is activated whenever the hash is accessed with a key specified as an \"SV\"\nthrough the functions \"hvstoreent\", \"hvfetchent\", \"hvdeleteent\", and \"hvexistsent\".\nAccessing the key as a string through the functions without the \"...ent\" suffix circumvents\nthe hook.  See \"GUTS\" in Hash::Util::FieldHash for a detailed description.\n\nNote that because multiple extensions may be using \"PERLMAGICext\" or \"PERLMAGICuvar\"\nmagic, it is important for extensions to take extra care to avoid conflict.  Typically only\nusing the magic on objects blessed into the same class as the extension is sufficient.  For\n\"PERLMAGICext\" magic, it is usually a good idea to define an \"MGVTBL\", even if all its\nfields will be 0, so that individual \"MAGIC\" pointers can be identified as a particular kind\nof magic using their magic virtual table.  \"mgfindext\" provides an easy way to do that:\n\nSTATIC MGVTBL myvtbl = { 0, 0, 0, 0, 0, 0, 0, 0 };\n\nMAGIC *mg;\nif ((mg = mgfindext(sv, PERLMAGICext, &myvtbl))) {\n/* this is really ours, not another module's PERLMAGICext */\nmyprivdatat *priv = (myprivdatat *)mg->mgptr;\n...\n}\n\nAlso note that the \"svset*()\" and \"svcat*()\" functions described earlier do not invoke\n'set' magic on their targets.  This must be done by the user either by calling the\n\"SvSETMAGIC()\" macro after calling these functions, or by using one of the \"svset*mg()\" or\n\"svcat*mg()\" functions.  Similarly, generic C code must call the \"SvGETMAGIC()\" macro to\ninvoke any 'get' magic if they use an SV obtained from external sources in functions that\ndon't handle magic.  See perlapi for a description of these functions.  For example, calls to\nthe \"svcat*()\" functions typically need to be followed by \"SvSETMAGIC()\", but they don't\nneed a prior \"SvGETMAGIC()\" since their implementation handles 'get' magic.\n"
                    },
                    {
                        "name": "Finding Magic",
                        "content": "MAGIC *mgfind(SV *sv, int type); /* Finds the magic pointer of that\n* type */\n\nThis routine returns a pointer to a \"MAGIC\" structure stored in the SV.  If the SV does not\nhave that magical feature, \"NULL\" is returned.  If the SV has multiple instances of that\nmagical feature, the first one will be returned.  \"mgfindext\" can be used to find a \"MAGIC\"\nstructure of an SV based on both its magic type and its magic virtual table:\n\nMAGIC *mgfindext(SV *sv, int type, MGVTBL *vtbl);\n\nAlso, if the SV passed to \"mgfind\" or \"mgfindext\" is not of type SVtPVMG, Perl may core\ndump.\n\nint mgcopy(SV* sv, SV* nsv, const char* key, STRLEN klen);\n\nThis routine checks to see what types of magic \"sv\" has.  If the mgtype field is an\nuppercase letter, then the mgobj is copied to \"nsv\", but the mgtype field is changed to be\nthe lowercase letter.\n"
                    },
                    {
                        "name": "Understanding the Magic of Tied Hashes and Arrays",
                        "content": "Tied hashes and arrays are magical beasts of the \"PERLMAGICtied\" magic type.\n\nWARNING: As of the 5.004 release, proper usage of the array and hash access functions\nrequires understanding a few caveats.  Some of these caveats are actually considered bugs in\nthe API, to be fixed in later releases, and are bracketed with [MAYCHANGE] below.  If you\nfind yourself actually applying such information in this section, be aware that the behavior\nmay change in the future, umm, without warning.\n\nThe perl tie function associates a variable with an object that implements the various GET,\nSET, etc methods.  To perform the equivalent of the perl tie function from an XSUB, you must\nmimic this behaviour.  The code below carries out the necessary steps -- firstly it creates a\nnew hash, and then creates a second hash which it blesses into the class which will implement\nthe tie methods.  Lastly it ties the two hashes together, and returns a reference to the new\ntied hash.  Note that the code below does NOT call the TIEHASH method in the MyTie class -\nsee \"Calling Perl Routines from within C Programs\" for details on how to do this.\n\nSV*\nmytie()\nPREINIT:\nHV *hash;\nHV *stash;\nSV *tie;\nCODE:\nhash = newHV();\ntie = newRVnoinc((SV*)newHV());\nstash = gvstashpv(\"MyTie\", GVADD);\nsvbless(tie, stash);\nhvmagic(hash, (GV*)tie, PERLMAGICtied);\nRETVAL = newRVnoinc(hash);\nOUTPUT:\nRETVAL\n\nThe \"avstore\" function, when given a tied array argument, merely copies the magic of the\narray onto the value to be \"stored\", using \"mgcopy\".  It may also return NULL, indicating\nthat the value did not actually need to be stored in the array.  [MAYCHANGE] After a call to\n\"avstore\" on a tied array, the caller will usually need to call \"mgset(val)\" to actually\ninvoke the perl level \"STORE\" method on the TIEARRAY object.  If \"avstore\" did return NULL,\na call to \"SvREFCNTdec(val)\" will also be usually necessary to avoid a memory leak.\n[/MAYCHANGE]\n\nThe previous paragraph is applicable verbatim to tied hash access using the \"hvstore\" and\n\"hvstoreent\" functions as well.\n\n\"avfetch\" and the corresponding hash functions \"hvfetch\" and \"hvfetchent\" actually return\nan undefined mortal value whose magic has been initialized using \"mgcopy\".  Note the value\nso returned does not need to be deallocated, as it is already mortal.  [MAYCHANGE] But you\nwill need to call \"mgget()\" on the returned value in order to actually invoke the perl level\n\"FETCH\" method on the underlying TIE object.  Similarly, you may also call \"mgset()\" on the\nreturn value after possibly assigning a suitable value to it using \"svsetsv\",  which will\ninvoke the \"STORE\" method on the TIE object. [/MAYCHANGE]\n\n[MAYCHANGE] In other words, the array or hash fetch/store functions don't really fetch and\nstore actual values in the case of tied arrays and hashes.  They merely call \"mgcopy\" to\nattach magic to the values that were meant to be \"stored\" or \"fetched\".  Later calls to\n\"mgget\" and \"mgset\" actually do the job of invoking the TIE methods on the underlying\nobjects.  Thus the magic mechanism currently implements a kind of lazy access to arrays and\nhashes.\n\nCurrently (as of perl version 5.004), use of the hash and array access functions requires the\nuser to be aware of whether they are operating on \"normal\" hashes and arrays, or on their\ntied variants.  The API may be changed to provide more transparent access to both tied and\nnormal data types in future versions.  [/MAYCHANGE]\n\nYou would do well to understand that the TIEARRAY and TIEHASH interfaces are mere sugar to\ninvoke some perl method calls while using the uniform hash and array syntax.  The use of this\nsugar imposes some overhead (typically about two to four extra opcodes per FETCH/STORE\noperation, in addition to the creation of all the mortal variables required to invoke the\nmethods).  This overhead will be comparatively small if the TIE methods are themselves\nsubstantial, but if they are only a few statements long, the overhead will not be\ninsignificant.\n"
                    },
                    {
                        "name": "Localizing changes",
                        "content": "Perl has a very handy construction\n\n{\nlocal $var = 2;\n...\n}\n\nThis construction is approximately equivalent to\n\n{\nmy $oldvar = $var;\n$var = 2;\n...\n$var = $oldvar;\n}\n\nThe biggest difference is that the first construction would reinstate the initial value of\n$var, irrespective of how control exits the block: \"goto\", \"return\", \"die\"/\"eval\", etc.  It\nis a little bit more efficient as well.\n\nThere is a way to achieve a similar task from C via Perl API: create a pseudo-block, and\narrange for some changes to be automatically undone at the end of it, either explicit, or via\na non-local exit (via die()).  A block-like construct is created by a pair of \"ENTER\"/\"LEAVE\"\nmacros (see \"Returning a Scalar\" in perlcall).  Such a construct may be created specially for\nsome important localized task, or an existing one (like boundaries of enclosing Perl\nsubroutine/block, or an existing pair for freeing TMPs) may be used.  (In the second case the\noverhead of additional localization must be almost negligible.)  Note that any XSUB is\nautomatically enclosed in an \"ENTER\"/\"LEAVE\" pair.\n\nInside such a pseudo-block the following service is available:\n\n\"SAVEINT(int i)\"\n\"SAVEIV(IV i)\"\n\"SAVEI32(I32 i)\"\n\"SAVELONG(long i)\"\n\"SAVEI8(I8 i)\"\n\"SAVEI16(I16 i)\"\n\"SAVEBOOL(int i)\"\nThese macros arrange things to restore the value of integer variable \"i\" at the end of\nthe enclosing pseudo-block.\n\nSAVESPTR(s)\nSAVEPPTR(p)\nThese macros arrange things to restore the value of pointers \"s\" and \"p\".  \"s\" must be a\npointer of a type which survives conversion to \"SV*\" and back, \"p\" should be able to\nsurvive conversion to \"char*\" and back.\n\n\"SAVEFREESV(SV *sv)\"\nThe refcount of \"sv\" will be decremented at the end of pseudo-block.  This is similar to\n\"sv2mortal\" in that it is also a mechanism for doing a delayed \"SvREFCNTdec\".  However,\nwhile \"sv2mortal\" extends the lifetime of \"sv\" until the beginning of the next\nstatement, \"SAVEFREESV\" extends it until the end of the enclosing scope.  These lifetimes\ncan be wildly different.\n\nAlso compare \"SAVEMORTALIZESV\".\n\n\"SAVEMORTALIZESV(SV *sv)\"\nJust like \"SAVEFREESV\", but mortalizes \"sv\" at the end of the current scope instead of\ndecrementing its reference count.  This usually has the effect of keeping \"sv\" alive\nuntil the statement that called the currently live scope has finished executing.\n\n\"SAVEFREEOP(OP *op)\"\nThe \"OP *\" is opfree()ed at the end of pseudo-block.\n\nSAVEFREEPV(p)\nThe chunk of memory which is pointed to by \"p\" is Safefree()ed at the end of pseudo-\nblock.\n\n\"SAVECLEARSV(SV *sv)\"\nClears a slot in the current scratchpad which corresponds to \"sv\" at the end of pseudo-\nblock.\n\n\"SAVEDELETE(HV *hv, char *key, I32 length)\"\nThe key \"key\" of \"hv\" is deleted at the end of pseudo-block.  The string pointed to by\n\"key\" is Safefree()ed.  If one has a key in short-lived storage, the corresponding string\nmay be reallocated like this:\n\nSAVEDELETE(PLdefstash, savepv(tmpbuf), strlen(tmpbuf));\n\n\"SAVEDESTRUCTOR(DESTRUCTORFUNCNOCONTEXTt f, void *p)\"\nAt the end of pseudo-block the function \"f\" is called with the only argument \"p\".\n\n\"SAVEDESTRUCTORX(DESTRUCTORFUNCt f, void *p)\"\nAt the end of pseudo-block the function \"f\" is called with the implicit context argument\n(if any), and \"p\".\n\n\"SAVESTACKPOS()\"\nThe current offset on the Perl internal stack (cf. \"SP\") is restored at the end of\npseudo-block.\n\nThe following API list contains functions, thus one needs to provide pointers to the\nmodifiable data explicitly (either C pointers, or Perlish \"GV *\"s).  Where the above macros\ntake \"int\", a similar function takes \"int *\".\n\nOther macros above have functions implementing them, but its probably best to just use the\nmacro, and not those or the ones below.\n\n\"SV* savescalar(GV *gv)\"\nEquivalent to Perl code \"local $gv\".\n\n\"AV* saveary(GV *gv)\"\n\"HV* savehash(GV *gv)\"\nSimilar to \"savescalar\", but localize @gv and %gv.\n\n\"void saveitem(SV *item)\"\nDuplicates the current value of \"SV\". On the exit from the current \"ENTER\"/\"LEAVE\"\npseudo-block the value of \"SV\" will be restored using the stored value.  It doesn't\nhandle magic.  Use \"savescalar\" if magic is affected.\n\n\"void savelist(SV sarg, I32 maxsarg)\"\nA variant of \"saveitem\" which takes multiple arguments via an array \"sarg\" of \"SV*\" of\nlength \"maxsarg\".\n\n\"SV* savesvref(SV sptr)\"\nSimilar to \"savescalar\", but will reinstate an \"SV *\".\n\n\"void saveaptr(AV aptr)\"\n\"void savehptr(HV hptr)\"\nSimilar to \"savesvref\", but localize \"AV *\" and \"HV *\".\n\nThe \"Alias\" module implements localization of the basic types within the caller's scope.\nPeople who are interested in how to localize things in the containing scope should take a\nlook there too.\n"
                    }
                ]
            },
            "Subroutines": {
                "content": "",
                "subsections": [
                    {
                        "name": "XSUBs and the Argument Stack",
                        "content": "The XSUB mechanism is a simple way for Perl programs to access C subroutines.  An XSUB\nroutine will have a stack that contains the arguments from the Perl program, and a way to map\nfrom the Perl data structures to a C equivalent.\n\nThe stack arguments are accessible through the ST(n) macro, which returns the \"n\"'th stack\nargument.  Argument 0 is the first argument passed in the Perl subroutine call.  These\narguments are \"SV*\", and can be used anywhere an \"SV*\" is used.\n\nMost of the time, output from the C routine can be handled through use of the RETVAL and\nOUTPUT directives.  However, there are some cases where the argument stack is not already\nlong enough to handle all the return values.  An example is the POSIX tzname() call, which\ntakes no arguments, but returns two, the local time zone's standard and summer time\nabbreviations.\n\nTo handle this situation, the PPCODE directive is used and the stack is extended using the\nmacro:\n\nEXTEND(SP, num);\n\nwhere \"SP\" is the macro that represents the local copy of the stack pointer, and \"num\" is the\nnumber of elements the stack should be extended by.\n\nNow that there is room on the stack, values can be pushed on it using \"PUSHs\" macro.  The\npushed values will often need to be \"mortal\" (See \"Reference Counts and Mortality\"):\n\nPUSHs(sv2mortal(newSViv(aninteger)))\nPUSHs(sv2mortal(newSVuv(anunsignedinteger)))\nPUSHs(sv2mortal(newSVnv(adouble)))\nPUSHs(sv2mortal(newSVpv(\"Some String\",0)))\n/* Although the last example is better written as the more\n* efficient: */\nPUSHs(newSVpvsflags(\"Some String\", SVsTEMP))\n\nAnd now the Perl program calling \"tzname\", the two values will be assigned as in:\n\n($standardabbrev, $summerabbrev) = POSIX::tzname;\n\nAn alternate (and possibly simpler) method to pushing values on the stack is to use the\nmacro:\n\nXPUSHs(SV*)\n\nThis macro automatically adjusts the stack for you, if needed.  Thus, you do not need to call\n\"EXTEND\" to extend the stack.\n\nDespite their suggestions in earlier versions of this document the macros \"(X)PUSH[iunp]\" are\nnot suited to XSUBs which return multiple results.  For that, either stick to the \"(X)PUSHs\"\nmacros shown above, or use the new \"m(X)PUSH[iunp]\" macros instead; see \"Putting a C value on\nPerl stack\".\n\nFor more information, consult perlxs and perlxstut.\n"
                    },
                    {
                        "name": "Autoloading with XSUBs",
                        "content": "If an AUTOLOAD routine is an XSUB, as with Perl subroutines, Perl puts the fully-qualified\nname of the autoloaded subroutine in the $AUTOLOAD variable of the XSUB's package.\n\nBut it also puts the same information in certain fields of the XSUB itself:\n\nHV *stash           = CvSTASH(cv);\nconst char *subname = SvPVX(cv);\nSTRLEN namelength  = SvCUR(cv); /* in bytes */\nU32 isutf8         = SvUTF8(cv);\n\n\"SvPVX(cv)\" contains just the sub name itself, not including the package.  For an AUTOLOAD\nroutine in UNIVERSAL or one of its superclasses, \"CvSTASH(cv)\" returns NULL during a method\ncall on a nonexistent package.\n\nNote: Setting $AUTOLOAD stopped working in 5.6.1, which did not support XS AUTOLOAD subs at\nall.  Perl 5.8.0 introduced the use of fields in the XSUB itself.  Perl 5.16.0 restored the\nsetting of $AUTOLOAD.  If you need to support 5.8-5.14, use the XSUB's fields.\n"
                    },
                    {
                        "name": "Calling Perl Routines from within C Programs",
                        "content": "There are four routines that can be used to call a Perl subroutine from within a C program.\nThese four are:\n\nI32  callsv(SV*, I32);\nI32  callpv(const char*, I32);\nI32  callmethod(const char*, I32);\nI32  callargv(const char*, I32, char);\n\nThe routine most often used is \"callsv\".  The \"SV*\" argument contains either the name of the\nPerl subroutine to be called, or a reference to the subroutine.  The second argument consists\nof flags that control the context in which the subroutine is called, whether or not the\nsubroutine is being passed arguments, how errors should be trapped, and how to treat return\nvalues.\n\nAll four routines return the number of arguments that the subroutine returned on the Perl\nstack.\n\nThese routines used to be called \"perlcallsv\", etc., before Perl v5.6.0, but those names\nare now deprecated; macros of the same name are provided for compatibility.\n\nWhen using any of these routines (except \"callargv\"), the programmer must manipulate the\nPerl stack.  These include the following macros and functions:\n\ndSP\nSP\nPUSHMARK()\nPUTBACK\nSPAGAIN\nENTER\nSAVETMPS\nFREETMPS\nLEAVE\nXPUSH*()\nPOP*()\n\nFor a detailed description of calling conventions from C to Perl, consult perlcall.\n"
                    },
                    {
                        "name": "Putting a C value on Perl stack",
                        "content": "A lot of opcodes (this is an elementary operation in the internal perl stack machine) put an\nSV* on the stack.  However, as an optimization the corresponding SV is (usually) not\nrecreated each time.  The opcodes reuse specially assigned SVs (targets) which are (as a\ncorollary) not constantly freed/created.\n\nEach of the targets is created only once (but see \"Scratchpads and recursion\" below), and\nwhen an opcode needs to put an integer, a double, or a string on stack, it just sets the\ncorresponding parts of its target and puts the target on stack.\n\nThe macro to put this target on stack is \"PUSHTARG\", and it is directly used in some opcodes,\nas well as indirectly in zillions of others, which use it via \"(X)PUSH[iunp]\".\n\nBecause the target is reused, you must be careful when pushing multiple values on the stack.\nThe following code will not do what you think:\n\nXPUSHi(10);\nXPUSHi(20);\n\nThis translates as \"set \"TARG\" to 10, push a pointer to \"TARG\" onto the stack; set \"TARG\" to\n20, push a pointer to \"TARG\" onto the stack\".  At the end of the operation, the stack does\nnot contain the values 10 and 20, but actually contains two pointers to \"TARG\", which we have\nset to 20.\n\nIf you need to push multiple different values then you should either use the \"(X)PUSHs\"\nmacros, or else use the new \"m(X)PUSH[iunp]\" macros, none of which make use of \"TARG\".  The\n\"(X)PUSHs\" macros simply push an SV* on the stack, which, as noted under \"XSUBs and the\nArgument Stack\", will often need to be \"mortal\".  The new \"m(X)PUSH[iunp]\" macros make this a\nlittle easier to achieve by creating a new mortal for you (via \"(X)PUSHmortal\"), pushing that\nonto the stack (extending it if necessary in the case of the \"mXPUSH[iunp]\" macros), and then\nsetting its value.  Thus, instead of writing this to \"fix\" the example above:\n\nXPUSHs(sv2mortal(newSViv(10)))\nXPUSHs(sv2mortal(newSViv(20)))\n\nyou can simply write:\n\nmXPUSHi(10)\nmXPUSHi(20)\n\nOn a related note, if you do use \"(X)PUSH[iunp]\", then you're going to need a \"dTARG\" in your\nvariable declarations so that the \"*PUSH*\" macros can make use of the local variable \"TARG\".\nSee also \"dTARGET\" and \"dXSTARG\".\n"
                    },
                    {
                        "name": "Scratchpads",
                        "content": "The question remains on when the SVs which are targets for opcodes are created.  The answer\nis that they are created when the current unit--a subroutine or a file (for opcodes for\nstatements outside of subroutines)--is compiled.  During this time a special anonymous Perl\narray is created, which is called a scratchpad for the current unit.\n\nA scratchpad keeps SVs which are lexicals for the current unit and are targets for opcodes.\nA previous version of this document stated that one can deduce that an SV lives on a\nscratchpad by looking on its flags: lexicals have \"SVsPADMY\" set, and targets have\n\"SVsPADTMP\" set.  But this has never been fully true.  \"SVsPADMY\" could be set on a\nvariable that no longer resides in any pad.  While targets do have \"SVsPADTMP\" set, it can\nalso be set on variables that have never resided in a pad, but nonetheless act like targets.\nAs of perl 5.21.5, the \"SVsPADMY\" flag is no longer used and is defined as 0.  \"SvPADMY()\"\nnow returns true for anything without \"SVsPADTMP\".\n\nThe correspondence between OPs and targets is not 1-to-1.  Different OPs in the compile tree\nof the unit can use the same target, if this would not conflict with the expected life of the\ntemporary.\n"
                    },
                    {
                        "name": "Scratchpads and recursion",
                        "content": "In fact it is not 100% true that a compiled unit contains a pointer to the scratchpad AV.  In\nfact it contains a pointer to an AV of (initially) one element, and this element is the\nscratchpad AV.  Why do we need an extra level of indirection?\n\nThe answer is recursion, and maybe threads.  Both these can create several execution pointers\ngoing into the same subroutine.  For the subroutine-child not write over the temporaries for\nthe subroutine-parent (lifespan of which covers the call to the child), the parent and the\nchild should have different scratchpads.  (And the lexicals should be separate anyway!)\n\nSo each subroutine is born with an array of scratchpads (of length 1).  On each entry to the\nsubroutine it is checked that the current depth of the recursion is not more than the length\nof this array, and if it is, new scratchpad is created and pushed into the array.\n\nThe targets on this scratchpad are \"undef\"s, but they are already marked with correct flags.\n"
                    },
                    {
                        "name": "Memory Allocation",
                        "content": ""
                    },
                    {
                        "name": "Allocation",
                        "content": "All memory meant to be used with the Perl API functions should be manipulated using the\nmacros described in this section.  The macros provide the necessary transparency between\ndifferences in the actual malloc implementation that is used within perl.\n\nThe following three macros are used to initially allocate memory :\n\nNewx(pointer, number, type);\nNewxc(pointer, number, type, cast);\nNewxz(pointer, number, type);\n\nThe first argument \"pointer\" should be the name of a variable that will point to the newly\nallocated memory.\n\nThe second and third arguments \"number\" and \"type\" specify how many of the specified type of\ndata structure should be allocated.  The argument \"type\" is passed to \"sizeof\".  The final\nargument to \"Newxc\", \"cast\", should be used if the \"pointer\" argument is different from the\n\"type\" argument.\n\nUnlike the \"Newx\" and \"Newxc\" macros, the \"Newxz\" macro calls \"memzero\" to zero out all the\nnewly allocated memory.\n"
                    },
                    {
                        "name": "Reallocation",
                        "content": "Renew(pointer, number, type);\nRenewc(pointer, number, type, cast);\nSafefree(pointer)\n\nThese three macros are used to change a memory buffer size or to free a piece of memory no\nlonger needed.  The arguments to \"Renew\" and \"Renewc\" match those of \"New\" and \"Newc\" with\nthe exception of not needing the \"magic cookie\" argument.\n"
                    },
                    {
                        "name": "Moving",
                        "content": "Move(source, dest, number, type);\nCopy(source, dest, number, type);\nZero(dest, number, type);\n\nThese three macros are used to move, copy, or zero out previously allocated memory.  The\n\"source\" and \"dest\" arguments point to the source and destination starting points.  Perl will\nmove, copy, or zero out \"number\" instances of the size of the \"type\" data structure (using\nthe \"sizeof\" function).\n"
                    }
                ]
            },
            "PerlIO": {
                "content": "The most recent development releases of Perl have been experimenting with removing Perl's\ndependency on the \"normal\" standard I/O suite and allowing other stdio implementations to be\nused.  This involves creating a new abstraction layer that then calls whichever\nimplementation of stdio Perl was compiled with.  All XSUBs should now use the functions in\nthe PerlIO abstraction layer and not make any assumptions about what kind of stdio is being\nused.\n\nFor a complete description of the PerlIO abstraction, consult perlapio.\n",
                "subsections": [
                    {
                        "name": "Compiled code",
                        "content": ""
                    },
                    {
                        "name": "Code tree",
                        "content": "Here we describe the internal form your code is converted to by Perl.  Start with a simple\nexample:\n\n$a = $b + $c;\n\nThis is converted to a tree similar to this one:\n\nassign-to\n/           \\\n+             $a\n/   \\\n$b     $c\n\n(but slightly more complicated).  This tree reflects the way Perl parsed your code, but has\nnothing to do with the execution order.  There is an additional \"thread\" going through the\nnodes of the tree which shows the order of execution of the nodes.  In our simplified example\nabove it looks like:\n\n$b ---> $c ---> + ---> $a ---> assign-to\n\nBut with the actual compile tree for \"$a = $b + $c\" it is different: some nodes optimized\naway.  As a corollary, though the actual tree contains more nodes than our simplified\nexample, the execution order is the same as in our example.\n"
                    },
                    {
                        "name": "Examining the tree",
                        "content": "If you have your perl compiled for debugging (usually done with \"-DDEBUGGING\" on the\n\"Configure\" command line), you may examine the compiled tree by specifying \"-Dx\" on the Perl\ncommand line.  The output takes several lines per node, and for \"$b+$c\" it looks like this:\n\n5           TYPE = add  ===> 6\nTARG = 1\nFLAGS = (SCALAR,KIDS)\n{\nTYPE = null  ===> (4)\n(was rv2sv)\nFLAGS = (SCALAR,KIDS)\n{\n3                   TYPE = gvsv  ===> 4\nFLAGS = (SCALAR)\nGV = main::b\n}\n}\n{\nTYPE = null  ===> (5)\n(was rv2sv)\nFLAGS = (SCALAR,KIDS)\n{\n4                   TYPE = gvsv  ===> 5\nFLAGS = (SCALAR)\nGV = main::c\n}\n}\n\nThis tree has 5 nodes (one per \"TYPE\" specifier), only 3 of them are not optimized away (one\nper number in the left column).  The immediate children of the given node correspond to \"{}\"\npairs on the same level of indentation, thus this listing corresponds to the tree:\n\nadd\n/     \\\nnull    null\n|       |\ngvsv    gvsv\n\nThe execution order is indicated by \"===>\" marks, thus it is \"3 4 5 6\" (node 6 is not\nincluded into above listing), i.e., \"gvsv gvsv add whatever\".\n\nEach of these nodes represents an op, a fundamental operation inside the Perl core.  The code\nwhich implements each operation can be found in the pp*.c files; the function which\nimplements the op with type \"gvsv\" is \"ppgvsv\", and so on.  As the tree above shows,\ndifferent ops have different numbers of children: \"add\" is a binary operator, as one would\nexpect, and so has two children.  To accommodate the various different numbers of children,\nthere are various types of op data structure, and they link together in different ways.\n\nThe simplest type of op structure is \"OP\": this has no children.  Unary operators, \"UNOP\"s,\nhave one child, and this is pointed to by the \"opfirst\" field.  Binary operators (\"BINOP\"s)\nhave not only an \"opfirst\" field but also an \"oplast\" field.  The most complex type of op\nis a \"LISTOP\", which has any number of children.  In this case, the first child is pointed to\nby \"opfirst\" and the last child by \"oplast\".  The children in between can be found by\niteratively following the \"OpSIBLING\" pointer from the first child to the last (but see\nbelow).\n\nThere are also some other op types: a \"PMOP\" holds a regular expression, and has no children,\nand a \"LOOP\" may or may not have children.  If the \"opchildren\" field is non-zero, it\nbehaves like a \"LISTOP\".  To complicate matters, if a \"UNOP\" is actually a \"null\" op after\noptimization (see \"Compile pass 2: context propagation\") it will still have children in\naccordance with its former type.\n\nFinally, there is a \"LOGOP\", or logic op. Like a \"LISTOP\", this has one or more children, but\nit doesn't have an \"oplast\" field: so you have to follow \"opfirst\" and then the \"OpSIBLING\"\nchain itself to find the last child. Instead it has an \"opother\" field, which is comparable\nto the \"opnext\" field described below, and represents an alternate execution path. Operators\nlike \"and\", \"or\" and \"?\" are \"LOGOP\"s. Note that in general, \"opother\" may not point to any\nof the direct children of the \"LOGOP\".\n\nStarting in version 5.21.2, perls built with the experimental define \"-DPERLOPPARENT\" add\nan extra boolean flag for each op, \"opmoresib\".  When not set, this indicates that this is\nthe last op in an \"OpSIBLING\" chain. This frees up the \"opsibling\" field on the last sibling\nto point back to the parent op. Under this build, that field is also renamed \"opsibparent\"\nto reflect its joint role. The macro OpSIBLING(o) wraps this special behaviour, and always\nreturns NULL on the last sibling.  With this build the opparent(o) function can be used to\nfind the parent of any op. Thus for forward compatibility, you should always use the\nOpSIBLING(o) macro rather than accessing \"opsibling\" directly.\n\nAnother way to examine the tree is to use a compiler back-end module, such as B::Concise.\n"
                    },
                    {
                        "name": "Compile pass 1: check routines",
                        "content": "The tree is created by the compiler while yacc code feeds it the constructions it recognizes.\nSince yacc works bottom-up, so does the first pass of perl compilation.\n\nWhat makes this pass interesting for perl developers is that some optimization may be\nperformed on this pass.  This is optimization by so-called \"check routines\".  The\ncorrespondence between node names and corresponding check routines is described in opcode.pl\n(do not forget to run \"make regenheaders\" if you modify this file).\n\nA check routine is called when the node is fully constructed except for the execution-order\nthread.  Since at this time there are no back-links to the currently constructed node, one\ncan do most any operation to the top-level node, including freeing it and/or creating new\nnodes above/below it.\n\nThe check routine returns the node which should be inserted into the tree (if the top-level\nnode was not modified, check routine returns its argument).\n\nBy convention, check routines have names \"ck*\".  They are usually called from \"new*OP\"\nsubroutines (or \"convert\") (which in turn are called from perly.y).\n"
                    },
                    {
                        "name": "Compile pass 1a: constant folding",
                        "content": "Immediately after the check routine is called the returned node is checked for being compile-\ntime executable.  If it is (the value is judged to be constant) it is immediately executed,\nand a constant node with the \"return value\" of the corresponding subtree is substituted\ninstead.  The subtree is deleted.\n\nIf constant folding was not performed, the execution-order thread is created.\n"
                    },
                    {
                        "name": "Compile pass 2: context propagation",
                        "content": "When a context for a part of compile tree is known, it is propagated down through the tree.\nAt this time the context can have 5 values (instead of 2 for runtime context): void, boolean,\nscalar, list, and lvalue.  In contrast with the pass 1 this pass is processed from top to\nbottom: a node's context determines the context for its children.\n\nAdditional context-dependent optimizations are performed at this time.  Since at this moment\nthe compile tree contains back-references (via \"thread\" pointers), nodes cannot be free()d\nnow.  To allow optimized-away nodes at this stage, such nodes are null()ified instead of\nfree()ing (i.e. their type is changed to OPNULL).\n"
                    },
                    {
                        "name": "Compile pass 3: peephole optimization",
                        "content": "After the compile tree for a subroutine (or for an \"eval\" or a file) is created, an\nadditional pass over the code is performed.  This pass is neither top-down or bottom-up, but\nin the execution order (with additional complications for conditionals).  Optimizations\nperformed at this stage are subject to the same restrictions as in the pass 2.\n\nPeephole optimizations are done by calling the function pointed to by the global variable\n\"PLpeepp\".  By default, \"PLpeepp\" just calls the function pointed to by the global variable\n\"PLrpeepp\".  By default, that performs some basic op fixups and optimisations along the\nexecution-order op chain, and recursively calls \"PLrpeepp\" for each side chain of ops\n(resulting from conditionals).  Extensions may provide additional optimisations or fixups,\nhooking into either the per-subroutine or recursive stage, like this:\n\nstatic peept prevpeepp;\nstatic void mypeep(pTHX OP *o)\n{\n/* custom per-subroutine optimisation goes here */\nprevpeepp(aTHX o);\n/* custom per-subroutine optimisation may also go here */\n}\nBOOT:\nprevpeepp = PLpeepp;\nPLpeepp = mypeep;\n\nstatic peept prevrpeepp;\nstatic void myrpeep(pTHX OP *first)\n{\nOP *o = first, *t = first;\nfor(; o = o->opnext, t = t->opnext) {\n/* custom per-op optimisation goes here */\no = o->opnext;\nif (!o || o == t) break;\n/* custom per-op optimisation goes AND here */\n}\nprevrpeepp(aTHX origo);\n}\nBOOT:\nprevrpeepp = PLrpeepp;\nPLrpeepp = myrpeep;\n"
                    },
                    {
                        "name": "Pluggable runops",
                        "content": "The compile tree is executed in a runops function.  There are two runops functions, in run.c\nand in dump.c.  \"Perlrunopsdebug\" is used with DEBUGGING and \"Perlrunopsstandard\" is used\notherwise.  For fine control over the execution of the compile tree it is possible to provide\nyour own runops function.\n\nIt's probably best to copy one of the existing runops functions and change it to suit your\nneeds.  Then, in the BOOT section of your XS file, add the line:\n\nPLrunops = myrunops;\n\nThis function should be as efficient as possible to keep your programs running as fast as\npossible.\n"
                    },
                    {
                        "name": "Compile-time scope hooks",
                        "content": "As of perl 5.14 it is possible to hook into the compile-time lexical scope mechanism using\n\"Perlblockhookregister\".  This is used like this:\n\nSTATIC void mystarthook(pTHX int full);\nSTATIC BHK myhooks;\n\nBOOT:\nBhkENTRYset(&myhooks, bhkstart, mystarthook);\nPerlblockhookregister(aTHX &myhooks);\n\nThis will arrange to have \"mystarthook\" called at the start of compiling every lexical\nscope.  The available hooks are:\n\n\"void bhkstart(pTHX int full)\"\nThis is called just after starting a new lexical scope.  Note that Perl code like\n\nif ($x) { ... }\n\ncreates two scopes: the first starts at the \"(\" and has \"full == 1\", the second starts at\nthe \"{\" and has \"full == 0\".  Both end at the \"}\", so calls to \"start\" and\n\"pre\"/\"postend\" will match.  Anything pushed onto the save stack by this hook will be\npopped just before the scope ends (between the \"pre\" and \"postend\" hooks, in fact).\n\n\"void bhkpreend(pTHX OP o)\"\nThis is called at the end of a lexical scope, just before unwinding the stack.  o is the\nroot of the optree representing the scope; it is a double pointer so you can replace the\nOP if you need to.\n\n\"void bhkpostend(pTHX OP o)\"\nThis is called at the end of a lexical scope, just after unwinding the stack.  o is as\nabove.  Note that it is possible for calls to \"pre\" and \"postend\" to nest, if there is\nsomething on the save stack that calls string eval.\n\n\"void bhkeval(pTHX OP *const o)\"\nThis is called just before starting to compile an \"eval STRING\", \"do FILE\", \"require\" or\n\"use\", after the eval has been set up.  o is the OP that requested the eval, and will\nnormally be an \"OPENTEREVAL\", \"OPDOFILE\" or \"OPREQUIRE\".\n\nOnce you have your hook functions, you need a \"BHK\" structure to put them in.  It's best to\nallocate it statically, since there is no way to free it once it's registered.  The function\npointers should be inserted into this structure using the \"BhkENTRYset\" macro, which will\nalso set flags indicating which entries are valid.  If you do need to allocate your \"BHK\"\ndynamically for some reason, be sure to zero it before you start.\n\nOnce registered, there is no mechanism to switch these hooks off, so if that is necessary you\nwill need to do this yourself.  An entry in \"%^H\" is probably the best way, so the effect is\nlexically scoped; however it is also possible to use the \"BhkDISABLE\" and \"BhkENABLE\" macros\nto temporarily switch entries on and off.  You should also be aware that generally speaking\nat least one scope will have opened before your extension is loaded, so you will see some\n\"pre\"/\"postend\" pairs that didn't have a matching \"start\".\n"
                    },
                    {
                        "name": "Examining internal data structures with the \"dump\" functions",
                        "content": "To aid debugging, the source file dump.c contains a number of functions which produce\nformatted output of internal data structures.\n\nThe most commonly used of these functions is \"Perlsvdump\"; it's used for dumping SVs, AVs,\nHVs, and CVs.  The \"Devel::Peek\" module calls \"svdump\" to produce debugging output from\nPerl-space, so users of that module should already be familiar with its format.\n\n\"Perlopdump\" can be used to dump an \"OP\" structure or any of its derivatives, and produces\noutput similar to \"perl -Dx\"; in fact, \"Perldumpeval\" will dump the main root of the code\nbeing evaluated, exactly like \"-Dx\".\n\nOther useful functions are \"Perldumpsub\", which turns a \"GV\" into an op tree,\n\"Perldumppacksubs\" which calls \"Perldumpsub\" on all the subroutines in a package like so:\n(Thankfully, these are all xsubs, so there is no op tree)\n\n(gdb) print Perldumppacksubs(PLdefstash)\n\nSUB attributes::bootstrap = (xsub 0x811fedc 0)\n\nSUB UNIVERSAL::can = (xsub 0x811f50c 0)\n\nSUB UNIVERSAL::isa = (xsub 0x811f304 0)\n\nSUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)\n\nSUB DynaLoader::bootDynaLoader = (xsub 0x805b188 0)\n\nand \"Perldumpall\", which dumps all the subroutines in the stash and the op tree of the main\nroot.\n"
                    },
                    {
                        "name": "How multiple interpreters and concurrency are supported",
                        "content": "Background and PERLIMPLICITCONTEXT\nThe Perl interpreter can be regarded as a closed box: it has an API for feeding it code or\notherwise making it do things, but it also has functions for its own use.  This smells a lot\nlike an object, and there is a way for you to build Perl so that you can have multiple\ninterpreters, with one interpreter represented either as a C structure, or inside a thread-\nspecific structure.  These structures contain all the context, the state of that interpreter.\n\nThe macro that controls the major Perl build flavor is MULTIPLICITY.  The MULTIPLICITY build\nhas a C structure that packages all the interpreter state.  With multiplicity-enabled perls,\nPERLIMPLICITCONTEXT is also normally defined, and enables the support for passing in a\n\"hidden\" first argument that represents all three data structures.  MULTIPLICITY makes multi-\nthreaded perls possible (with the ithreads threading model, related to the macro\nUSEITHREADS.)\n\nTo see whether you have non-const data you can use a BSD (or GNU) compatible \"nm\":\n\nnm libperl.a | grep -v ' [TURtr] '\n\nIf this displays any \"D\" or \"d\" symbols (or possibly \"C\" or \"c\"), you have non-const data.\nThe symbols the \"grep\" removed are as follows: \"Tt\" are text, or code, the \"Rr\" are read-only\n(const) data, and the \"U\" is <undefined>, external symbols referred to.\n\nThe test t/porting/libperl.t does this kind of symbol sanity checking on \"libperl.a\".\n\nAll this obviously requires a way for the Perl internal functions to be either subroutines\ntaking some kind of structure as the first argument, or subroutines taking nothing as the\nfirst argument.  To enable these two very different ways of building the interpreter, the\nPerl source (as it does in so many other situations) makes heavy use of macros and subroutine\nnaming conventions.\n\nFirst problem: deciding which functions will be public API functions and which will be\nprivate.  All functions whose names begin \"S\" are private (think \"S\" for \"secret\" or\n\"static\").  All other functions begin with \"Perl\", but just because a function begins with\n\"Perl\" does not mean it is part of the API.  (See \"Internal Functions\".)  The easiest way to\nbe sure a function is part of the API is to find its entry in perlapi.  If it exists in\nperlapi, it's part of the API.  If it doesn't, and you think it should be (i.e., you need it\nfor your extension), submit an issue at <https://github.com/Perl/perl5/issues> explaining why\nyou think it should be.\n\nSecond problem: there must be a syntax so that the same subroutine declarations and calls can\npass a structure as their first argument, or pass nothing.  To solve this, the subroutines\nare named and declared in a particular way.  Here's a typical start of a static function used\nwithin the Perl guts:\n\nSTATIC void\nSincline(pTHX char *s)\n\nSTATIC becomes \"static\" in C, and may be #define'd to nothing in some configurations in the\nfuture.\n\nA public function (i.e. part of the internal API, but not necessarily sanctioned for use in\nextensions) begins like this:\n\nvoid\nPerlsvsetiv(pTHX SV* dsv, IV num)\n\n\"pTHX\" is one of a number of macros (in perl.h) that hide the details of the interpreter's\ncontext.  THX stands for \"thread\", \"this\", or \"thingy\", as the case may be.  (And no, George\nLucas is not involved. :-) The first character could be 'p' for a prototype, 'a' for\nargument, or 'd' for declaration, so we have \"pTHX\", \"aTHX\" and \"dTHX\", and their variants.\n\nWhen Perl is built without options that set PERLIMPLICITCONTEXT, there is no first argument\ncontaining the interpreter's context.  The trailing underscore in the pTHX macro indicates\nthat the macro expansion needs a comma after the context argument because other arguments\nfollow it.  If PERLIMPLICITCONTEXT is not defined, pTHX will be ignored, and the\nsubroutine is not prototyped to take the extra argument.  The form of the macro without the\ntrailing underscore is used when there are no additional explicit arguments.\n\nWhen a core function calls another, it must pass the context.  This is normally hidden via\nmacros.  Consider \"svsetiv\".  It expands into something like this:\n\n#ifdef PERLIMPLICITCONTEXT\n#define svsetiv(a,b)      Perlsvsetiv(aTHX a, b)\n/* can't do this for vararg functions, see below */\n#else\n#define svsetiv           Perlsvsetiv\n#endif\n\nThis works well, and means that XS authors can gleefully write:\n\nsvsetiv(foo, bar);\n\nand still have it work under all the modes Perl could have been compiled with.\n\nThis doesn't work so cleanly for varargs functions, though, as macros imply that the number\nof arguments is known in advance.  Instead we either need to spell them out fully, passing\n\"aTHX\" as the first argument (the Perl core tends to do this with functions like\nPerlwarner), or use a context-free version.\n\nThe context-free version of Perlwarner is called Perlwarnernocontext, and does not take\nthe extra argument.  Instead it does \"dTHX;\" to get the context from thread-local storage.\nWe \"#define warner Perlwarnernocontext\" so that extensions get source compatibility at the\nexpense of performance.  (Passing an arg is cheaper than grabbing it from thread-local\nstorage.)\n\nYou can ignore [pad]THXx when browsing the Perl headers/sources.  Those are strictly for use\nwithin the core.  Extensions and embedders need only be aware of [pad]THX.\n"
                    },
                    {
                        "name": "So what happened to dTHR?",
                        "content": "\"dTHR\" was introduced in perl 5.005 to support the older thread model.  The older thread\nmodel now uses the \"THX\" mechanism to pass context pointers around, so \"dTHR\" is not useful\nany more.  Perl 5.6.0 and later still have it for backward source compatibility, but it is\ndefined to be a no-op.\n"
                    },
                    {
                        "name": "How do I use all this in extensions?",
                        "content": "When Perl is built with PERLIMPLICITCONTEXT, extensions that call any functions in the Perl\nAPI will need to pass the initial context argument somehow.  The kicker is that you will need\nto write it in such a way that the extension still compiles when Perl hasn't been built with\nPERLIMPLICITCONTEXT enabled.\n\nThere are three ways to do this.  First, the easy but inefficient way, which is also the\ndefault, in order to maintain source compatibility with extensions: whenever XSUB.h is\n#included, it redefines the aTHX and aTHX macros to call a function that will return the\ncontext.  Thus, something like:\n\nsvsetiv(sv, num);\n\nin your extension will translate to this when PERLIMPLICITCONTEXT is in effect:\n\nPerlsvsetiv(Perlgetcontext(), sv, num);\n\nor to this otherwise:\n\nPerlsvsetiv(sv, num);\n\nYou don't have to do anything new in your extension to get this; since the Perl library\nprovides Perlgetcontext(), it will all just work.\n\nThe second, more efficient way is to use the following template for your Foo.xs:\n\n#define PERLNOGETCONTEXT     /* we want efficiency */\n#include \"EXTERN.h\"\n#include \"perl.h\"\n#include \"XSUB.h\"\n\nSTATIC void myprivatefunction(int arg1, int arg2);\n\nSTATIC void\nmyprivatefunction(int arg1, int arg2)\n{\ndTHX;       /* fetch context */\n... call many Perl API functions ...\n}\n\n[... etc ...]\n\nMODULE = Foo            PACKAGE = Foo\n\n/* typical XSUB */\n\nvoid\nmyxsub(arg)\nint arg\nCODE:\nmyprivatefunction(arg, 10);\n\nNote that the only two changes from the normal way of writing an extension is the addition of\na \"#define PERLNOGETCONTEXT\" before including the Perl headers, followed by a \"dTHX;\"\ndeclaration at the start of every function that will call the Perl API.  (You'll know which\nfunctions need this, because the C compiler will complain that there's an undeclared\nidentifier in those functions.)  No changes are needed for the XSUBs themselves, because the\nXS() macro is correctly defined to pass in the implicit context if needed.\n\nThe third, even more efficient way is to ape how it is done within the Perl guts:\n\n#define PERLNOGETCONTEXT     /* we want efficiency */\n#include \"EXTERN.h\"\n#include \"perl.h\"\n#include \"XSUB.h\"\n\n/* pTHX only needed for functions that call Perl API */\nSTATIC void myprivatefunction(pTHX int arg1, int arg2);\n\nSTATIC void\nmyprivatefunction(pTHX int arg1, int arg2)\n{\n/* dTHX; not needed here, because THX is an argument */\n... call Perl API functions ...\n}\n\n[... etc ...]\n\nMODULE = Foo            PACKAGE = Foo\n\n/* typical XSUB */\n\nvoid\nmyxsub(arg)\nint arg\nCODE:\nmyprivatefunction(aTHX arg, 10);\n\nThis implementation never has to fetch the context using a function call, since it is always\npassed as an extra argument.  Depending on your needs for simplicity or efficiency, you may\nmix the previous two approaches freely.\n\nNever add a comma after \"pTHX\" yourself--always use the form of the macro with the underscore\nfor functions that take explicit arguments, or the form without the argument for functions\nwith no explicit arguments.\n"
                    },
                    {
                        "name": "Should I do anything special if I call perl from multiple threads?",
                        "content": "If you create interpreters in one thread and then proceed to call them in another, you need\nto make sure perl's own Thread Local Storage (TLS) slot is initialized correctly in each of\nthose threads.\n\nThe \"perlalloc\" and \"perlclone\" API functions will automatically set the TLS slot to the\ninterpreter they created, so that there is no need to do anything special if the interpreter\nis always accessed in the same thread that created it, and that thread did not create or call\nany other interpreters afterwards.  If that is not the case, you have to set the TLS slot of\nthe thread before calling any functions in the Perl API on that particular interpreter.  This\nis done by calling the \"PERLSETCONTEXT\" macro in that thread as the first thing you do:\n\n/* do this before doing anything else with someperl */\nPERLSETCONTEXT(someperl);\n\n... other Perl API calls on someperl go here ...\n\nFuture Plans and PERLIMPLICITSYS\nJust as PERLIMPLICITCONTEXT provides a way to bundle up everything that the interpreter\nknows about itself and pass it around, so too are there plans to allow the interpreter to\nbundle up everything it knows about the environment it's running on.  This is enabled with\nthe PERLIMPLICITSYS macro.  Currently it only works with USEITHREADS on Windows.\n\nThis allows the ability to provide an extra pointer (called the \"host\" environment) for all\nthe system calls.  This makes it possible for all the system stuff to maintain their own\nstate, broken down into seven C structures.  These are thin wrappers around the usual system\ncalls (see win32/perllib.c) for the default perl executable, but for a more ambitious host\n(like the one that would do fork() emulation) all the extra work needed to pretend that\ndifferent interpreters are actually different \"processes\", would be done here.\n\nThe Perl engine/interpreter and the host are orthogonal entities.  There could be one or more\ninterpreters in a process, and one or more \"hosts\", with free association between them.\n"
                    },
                    {
                        "name": "Internal Functions",
                        "content": "All of Perl's internal functions which will be exposed to the outside world are prefixed by\n\"Perl\" so that they will not conflict with XS functions or functions used in a program in\nwhich Perl is embedded.  Similarly, all global variables begin with \"PL\".  (By convention,\nstatic functions start with \"S\".)\n\nInside the Perl core (\"PERLCORE\" defined), you can get at the functions either with or\nwithout the \"Perl\" prefix, thanks to a bunch of defines that live in embed.h.  Note that\nextension code should not set \"PERLCORE\"; this exposes the full perl internals, and is\nlikely to cause breakage of the XS in each new perl release.\n\nThe file embed.h is generated automatically from embed.pl and embed.fnc.  embed.pl also\ncreates the prototyping header files for the internal functions, generates the documentation\nand a lot of other bits and pieces.  It's important that when you add a new function to the\ncore or change an existing one, you change the data in the table in embed.fnc as well.\nHere's a sample entry from that table:\n\nApd |SV   |avfetch   |AV* ar|I32 key|I32 lval\n\nThe first column is a set of flags, the second column the return type, the third column the\nname.  Columns after that are the arguments.  The flags are documented at the top of\nembed.fnc.\n\nIf you edit embed.pl or embed.fnc, you will need to run \"make regenheaders\" to force a\nrebuild of embed.h and other auto-generated files.\n"
                    },
                    {
                        "name": "Formatted Printing of IVs, UVs, and NVs",
                        "content": "If you are printing IVs, UVs, or NVS instead of the stdio(3) style formatting codes like %d,\n%ld, %f, you should use the following macros for portability\n\nIVdf            IV in decimal\nUVuf            UV in decimal\nUVof            UV in octal\nUVxf            UV in hexadecimal\nNVef            NV %e-like\nNVff            NV %f-like\nNVgf            NV %g-like\n\nThese will take care of 64-bit integers and long doubles.  For example:\n\nprintf(\"IV is %\" IVdf \"\\n\", iv);\n\nThe \"IVdf\" will expand to whatever is the correct format for the IVs.  Note that the spaces\nare required around the format in case the code is compiled with C++, to maintain compliance\nwith its standard.\n\nNote that there are different \"long doubles\": Perl will use whatever the compiler has.\n\nIf you are printing addresses of pointers, use %p or UVxf combined with PTR2UV().\n"
                    },
                    {
                        "name": "Formatted Printing of SVs",
                        "content": "The contents of SVs may be printed using the \"SVf\" format, like so:\n\nPerlcroak(aTHX \"This croaked because: %\" SVf \"\\n\", SVfARG(errmsg))\n\nwhere \"errmsg\" is an SV.\n\nNot all scalar types are printable.  Simple values certainly are: one of IV, UV, NV, or PV.\nAlso, if the SV is a reference to some value, either it will be dereferenced and the value\nprinted, or information about the type of that value and its address are displayed.  The\nresults of printing any other type of SV are undefined and likely to lead to an interpreter\ncrash.  NVs are printed using a %g-ish format.\n\nNote that the spaces are required around the \"SVf\" in case the code is compiled with C++, to\nmaintain compliance with its standard.\n\nNote that any filehandle being printed to under UTF-8 must be expecting UTF-8 in order to get\ngood results and avoid Wide-character warnings.  One way to do this for typical filehandles\nis to invoke perl with the \"-C\"> parameter.  (See \"-C [number/list]\" in perlrun.\n\nYou can use this to concatenate two scalars:\n\nSV *var1 = getsv(\"var1\", GVADD);\nSV *var2 = getsv(\"var2\", GVADD);\nSV *var3 = newSVpvf(\"var1=%\" SVf \" and var2=%\" SVf,\nSVfARG(var1), SVfARG(var2));\n"
                    },
                    {
                        "name": "Formatted Printing of Strings",
                        "content": "If you just want the bytes printed in a 7bit NUL-terminated string, you can just use %s\n(assuming they are all really only 7bit).  But if there is a possibility the value will be\nencoded as UTF-8 or contains bytes above 0x7F (and therefore 8bit), you should instead use\nthe \"UTF8f\" format.  And as its parameter, use the \"UTF8fARG()\" macro:\n\nchr * msg;\n\n/* U+2018: \\xE2\\x80\\x98 LEFT SINGLE QUOTATION MARK\nU+2019: \\xE2\\x80\\x99 RIGHT SINGLE QUOTATION MARK */\nif (canutf8)\nmsg = \"\\xE2\\x80\\x98Uses fancy quotes\\xE2\\x80\\x99\";\nelse\nmsg = \"'Uses simple quotes'\";\n\nPerlcroak(aTHX \"The message is: %\" UTF8f \"\\n\",\nUTF8fARG(canutf8, strlen(msg), msg));\n\nThe first parameter to \"UTF8fARG\" is a boolean: 1 if the string is in UTF-8; 0 if string is\nin native byte encoding (Latin1).  The second parameter is the number of bytes in the string\nto print.  And the third and final parameter is a pointer to the first byte in the string.\n\nNote that any filehandle being printed to under UTF-8 must be expecting UTF-8 in order to get\ngood results and avoid Wide-character warnings.  One way to do this for typical filehandles\nis to invoke perl with the \"-C\"> parameter.  (See \"-C [number/list]\" in perlrun.\n\nFormatted Printing of \"Sizet\" and \"SSizet\"\nThe most general way to do this is to cast them to a UV or IV, and print as in the previous\nsection.\n\nBut if you're using \"PerlIOprintf()\", it's less typing and visual clutter to use the %z\nlength modifier (for siZe):\n\nPerlIOprintf(\"STRLEN is %zu\\n\", len);\n\nThis modifier is not portable, so its use should be restricted to \"PerlIOprintf()\".\n\nFormatted Printing of \"Ptrdifft\", \"intmaxt\", \"short\" and other special sizes\nThere are modifiers for these special situations if you are using \"PerlIOprintf()\".  See\n\"size\" in perlfunc.\n"
                    },
                    {
                        "name": "Pointer-To-Integer and Integer-To-Pointer",
                        "content": "Because pointer size does not necessarily equal integer size, use the follow macros to do it\nright.\n\nPTR2UV(pointer)\nPTR2IV(pointer)\nPTR2NV(pointer)\nINT2PTR(pointertotype, integer)\n\nFor example:\n\nIV  iv = ...;\nSV *sv = INT2PTR(SV*, iv);\n\nand\n\nAV *av = ...;\nUV  uv = PTR2UV(av);\n\nThere are also\n\nPTR2nat(pointer)   /* pointer to integer of PTRSIZE */\nPTR2ul(pointer)    /* pointer to unsigned long */\n\nAnd \"PTRV\" which gives the native type for an integer the same size as pointers, such as\n\"unsigned\" or \"unsigned long\".\n"
                    },
                    {
                        "name": "Exception Handling",
                        "content": "There are a couple of macros to do very basic exception handling in XS modules.  You have to\ndefine \"NOXSLOCKS\" before including XSUB.h to be able to use these macros:\n\n#define NOXSLOCKS\n#include \"XSUB.h\"\n\nYou can use these macros if you call code that may croak, but you need to do some cleanup\nbefore giving control back to Perl.  For example:\n\ndXCPT;    /* set up necessary variables */\n\nXCPTTRYSTART {\ncodethatmaycroak();\n} XCPTTRYEND\n\nXCPTCATCH\n{\n/* do cleanup here */\nXCPTRETHROW;\n}\n\nNote that you always have to rethrow an exception that has been caught.  Using these macros,\nit is not possible to just catch the exception and ignore it.  If you have to ignore the\nexception, you have to use the \"call*\" function.\n\nThe advantage of using the above macros is that you don't have to setup an extra function for\n\"call*\", and that using these macros is faster than using \"call*\".\n"
                    },
                    {
                        "name": "Source Documentation",
                        "content": "There's an effort going on to document the internal functions and automatically produce\nreference manuals from them -- perlapi is one such manual which details all the functions\nwhich are available to XS writers.  perlintern is the autogenerated manual for the functions\nwhich are not part of the API and are supposedly for internal use only.\n\nSource documentation is created by putting POD comments into the C source, like this:\n\n/*\n=for apidoc svsetiv\n\nCopies an integer into the given SV.  Does not handle 'set' magic.  See\nL<perlapi/svsetivmg>.\n\n=cut\n*/\n\nPlease try and supply some documentation if you add functions to the Perl core.\n"
                    },
                    {
                        "name": "Backwards compatibility",
                        "content": "The Perl API changes over time.  New functions are added or the interfaces of existing\nfunctions are changed.  The \"Devel::PPPort\" module tries to provide compatibility code for\nsome of these changes, so XS writers don't have to code it themselves when supporting\nmultiple versions of Perl.\n\n\"Devel::PPPort\" generates a C header file ppport.h that can also be run as a Perl script.  To\ngenerate ppport.h, run:\n\nperl -MDevel::PPPort -eDevel::PPPort::WriteFile\n\nBesides checking existing XS code, the script can also be used to retrieve compatibility\ninformation for various API calls using the \"--api-info\" command line switch.  For example:\n\n% perl ppport.h --api-info=svmagicext\n\nFor details, see \"perldoc ppport.h\".\n"
                    },
                    {
                        "name": "Unicode Support",
                        "content": "Perl 5.6.0 introduced Unicode support.  It's important for porters and XS writers to\nunderstand this support and make sure that the code they write does not corrupt Unicode data.\n"
                    },
                    {
                        "name": "What is Unicode, anyway?",
                        "content": "In the olden, less enlightened times, we all used to use ASCII.  Most of us did, anyway.  The\nbig problem with ASCII is that it's American.  Well, no, that's not actually the problem; the\nproblem is that it's not particularly useful for people who don't use the Roman alphabet.\nWhat used to happen was that particular languages would stick their own alphabet in the upper\nrange of the sequence, between 128 and 255.  Of course, we then ended up with plenty of\nvariants that weren't quite ASCII, and the whole point of it being a standard was lost.\n\nWorse still, if you've got a language like Chinese or Japanese that has hundreds or thousands\nof characters, then you really can't fit them into a mere 256, so they had to forget about\nASCII altogether, and build their own systems using pairs of numbers to refer to one\ncharacter.\n\nTo fix this, some people formed Unicode, Inc. and produced a new character set containing all\nthe characters you can possibly think of and more.  There are several ways of representing\nthese characters, and the one Perl uses is called UTF-8.  UTF-8 uses a variable number of\nbytes to represent a character.  You can learn more about Unicode and Perl's Unicode model in\nperlunicode.\n\n(On EBCDIC platforms, Perl uses instead UTF-EBCDIC, which is a form of UTF-8 adapted for\nEBCDIC platforms.  Below, we just talk about UTF-8.  UTF-EBCDIC is like UTF-8, but the\ndetails are different.  The macros hide the differences from you, just remember that the\nparticular numbers and bit patterns presented below will differ in UTF-EBCDIC.)\n"
                    },
                    {
                        "name": "How can I recognise a UTF-8 string?",
                        "content": "You can't.  This is because UTF-8 data is stored in bytes just like non-UTF-8 data.  The\nUnicode character 200, (0xC8 for you hex types) capital E with a grave accent, is represented\nby the two bytes \"v196.172\".  Unfortunately, the non-Unicode string \"chr(196).chr(172)\" has\nthat byte sequence as well.  So you can't tell just by looking -- this is what makes Unicode\ninput an interesting problem.\n\nIn general, you either have to know what you're dealing with, or you have to guess.  The API\nfunction \"isutf8string\" can help; it'll tell you if a string contains only valid UTF-8\ncharacters, and the chances of a non-UTF-8 string looking like valid UTF-8 become very small\nvery quickly with increasing string length.  On a character-by-character basis, \"isUTF8CHAR\"\nwill tell you whether the current character in a string is valid UTF-8.\n"
                    },
                    {
                        "name": "How does UTF-8 represent Unicode characters?",
                        "content": "As mentioned above, UTF-8 uses a variable number of bytes to store a character.  Characters\nwith values 0...127 are stored in one byte, just like good ol' ASCII.  Character 128 is\nstored as \"v194.128\"; this continues up to character 191, which is \"v194.191\".  Now we've run\nout of bits (191 is binary 10111111) so we move on; character 192 is \"v195.128\".  And so it\ngoes on, moving to three bytes at character 2048.  \"Unicode Encodings\" in perlunicode has\npictures of how this works.\n\nAssuming you know you're dealing with a UTF-8 string, you can find out how long the first\ncharacter in it is with the \"UTF8SKIP\" macro:\n\nchar *utf = \"\\305\\233\\340\\240\\201\";\nI32 len;\n\nlen = UTF8SKIP(utf); /* len is 2 here */\nutf += len;\nlen = UTF8SKIP(utf); /* len is 3 here */\n\nAnother way to skip over characters in a UTF-8 string is to use \"utf8hop\", which takes a\nstring and a number of characters to skip over.  You're on your own about bounds checking,\nthough, so don't use it lightly.\n\nAll bytes in a multi-byte UTF-8 character will have the high bit set, so you can test if you\nneed to do something special with this character like this (the \"UTF8ISINVARIANT()\" is a\nmacro that tests whether the byte is encoded as a single byte even in UTF-8):\n\nU8 *utf;     /* Initialize this to point to the beginning of the\nsequence to convert */\nU8 *utfend; /* Initialize this to 1 beyond the end of the sequence\npointed to by 'utf' */\nUV uv;       /* Returned code point; note: a UV, not a U8, not a\nchar */\nSTRLEN len; /* Returned length of character in bytes */\n\nif (!UTF8ISINVARIANT(*utf))\n/* Must treat this as UTF-8 */\nuv = utf8touvchrbuf(utf, utfend, &len);\nelse\n/* OK to treat this character as a byte */\nuv = *utf;\n\nYou can also see in that example that we use \"utf8touvchrbuf\" to get the value of the\ncharacter; the inverse function \"uvchrtoutf8\" is available for putting a UV into UTF-8:\n\nif (!UVCHRISINVARIANT(uv))\n/* Must treat this as UTF8 */\nutf8 = uvchrtoutf8(utf8, uv);\nelse\n/* OK to treat this character as a byte */\n*utf8++ = uv;\n\nYou must convert characters to UVs using the above functions if you're ever in a situation\nwhere you have to match UTF-8 and non-UTF-8 characters.  You may not skip over UTF-8\ncharacters in this case.  If you do this, you'll lose the ability to match hi-bit non-UTF-8\ncharacters; for instance, if your UTF-8 string contains \"v196.172\", and you skip that\ncharacter, you can never match a \"chr(200)\" in a non-UTF-8 string.  So don't do that!\n\n(Note that we don't have to test for invariant characters in the examples above.  The\nfunctions work on any well-formed UTF-8 input.  It's just that its faster to avoid the\nfunction overhead when it's not needed.)\n"
                    },
                    {
                        "name": "How does Perl store UTF-8 strings?",
                        "content": "Currently, Perl deals with UTF-8 strings and non-UTF-8 strings slightly differently.  A flag\nin the SV, \"SVfUTF8\", indicates that the string is internally encoded as UTF-8.  Without it,\nthe byte value is the codepoint number and vice versa.  This flag is only meaningful if the\nSV is \"SvPOK\" or immediately after stringification via \"SvPV\" or a similar macro.  You can\ncheck and manipulate this flag with the following macros:\n\nSvUTF8(sv)\nSvUTF8on(sv)\nSvUTF8off(sv)\n\nThis flag has an important effect on Perl's treatment of the string: if UTF-8 data is not\nproperly distinguished, regular expressions, \"length\", \"substr\" and other string handling\noperations will have undesirable (wrong) results.\n\nThe problem comes when you have, for instance, a string that isn't flagged as UTF-8, and\ncontains a byte sequence that could be UTF-8 -- especially when combining non-UTF-8 and UTF-8\nstrings.\n\nNever forget that the \"SVfUTF8\" flag is separate from the PV value; you need to be sure you\ndon't accidentally knock it off while you're manipulating SVs.  More specifically, you cannot\nexpect to do this:\n\nSV *sv;\nSV *nsv;\nSTRLEN len;\nchar *p;\n\np = SvPV(sv, len);\nfrobnicate(p);\nnsv = newSVpvn(p, len);\n\nThe \"char*\" string does not tell you the whole story, and you can't copy or reconstruct an SV\njust by copying the string value.  Check if the old SV has the UTF8 flag set (after the\n\"SvPV\" call), and act accordingly:\n\np = SvPV(sv, len);\nisutf8 = SvUTF8(sv);\nfrobnicate(p, isutf8);\nnsv = newSVpvn(p, len);\nif (isutf8)\nSvUTF8on(nsv);\n\nIn the above, your \"frobnicate\" function has been changed to be made aware of whether or not\nit's dealing with UTF-8 data, so that it can handle the string appropriately.\n\nSince just passing an SV to an XS function and copying the data of the SV is not enough to\ncopy the UTF8 flags, even less right is just passing a \"char *\" to an XS function.\n\nFor full generality, use the \"DOUTF8\" macro to see if the string in an SV is to be treated\nas UTF-8.  This takes into account if the call to the XS function is being made from within\nthe scope of \"use bytes\".  If so, the underlying bytes that comprise the UTF-8 string are to\nbe exposed, rather than the character they represent.  But this pragma should only really be\nused for debugging and perhaps low-level testing at the byte level.  Hence most XS code need\nnot concern itself with this, but various areas of the perl core do need to support it.\n\nAnd this isn't the whole story.  Starting in Perl v5.12, strings that aren't encoded in UTF-8\nmay also be treated as Unicode under various conditions (see \"ASCII Rules versus Unicode\nRules\" in perlunicode).  This is only really a problem for characters whose ordinals are\nbetween 128 and 255, and their behavior varies under ASCII versus Unicode rules in ways that\nyour code cares about (see \"The \"Unicode Bug\"\" in perlunicode).  There is no published API\nfor dealing with this, as it is subject to change, but you can look at the code for \"pplc\"\nin pp.c for an example as to how it's currently done.\n"
                    },
                    {
                        "name": "How do I pass a Perl string to a C library?",
                        "content": "A Perl string, conceptually, is an opaque sequence of code points.  Many C libraries expect\ntheir inputs to be \"classical\" C strings, which are arrays of octets 1-255, terminated with a\nNUL byte. Your job when writing an interface between Perl and a C library is to define the\nmapping between Perl and that library.\n\nGenerally speaking, \"SvPVbyte\" and related macros suit this task well.  These assume that\nyour Perl string is a \"byte string\", i.e., is either raw, undecoded input into Perl or is\npre-encoded to, e.g., UTF-8.\n\nAlternatively, if your C library expects UTF-8 text, you can use \"SvPVutf8\" and related\nmacros. This has the same effect as encoding to UTF-8 then calling the corresponding\n\"SvPVbyte\"-related macro.\n\nSome C libraries may expect other encodings (e.g., UTF-16LE). To give Perl strings to such\nlibraries you must either do that encoding in Perl then use \"SvPVbyte\", or use an\nintermediary C library to convert from however Perl stores the string to the desired\nencoding.\n\nTake care also that NULs in your Perl string don't confuse the C library. If possible, give\nthe string's length to the C library; if that's not possible, consider rejecting strings that\ncontain NUL bytes.\n\nWhat about \"SvPV\", \"SvPVnolen\", etc.?\n\nConsider a 3-character Perl string \"$foo = \"\\x64\\x78\\x8c\"\".  Perl can store these 3\ncharacters either of two ways:\n\n•   bytes: 0x64 0x78 0x8c\n\n•   UTF-8: 0x64 0x78 0xc2 0x8c\n\nNow let's say you convert $foo to a C string thus:\n\nSTRLEN strlen;\nchar *str = SvPV(foosv, strlen);\n\nAt this point \"str\" could point to a 3-byte C string or a 4-byte one.\n\nGenerally speaking, we want \"str\" to be the same regardless of how Perl stores $foo, so the\nambiguity here is undesirable. \"SvPVbyte\" and \"SvPVutf8\" solve that by giving predictable\noutput: use \"SvPVbyte\" if your C library expects byte strings, or \"SvPVutf8\" if it expects\nUTF-8.\n\nIf your C library happens to support both encodings, then \"SvPV\"--always in tandem with\nlookups to \"SvUTF8\"!--may be safe and (slightly) more efficient.\n\nTESTING TIP: Use utf8's \"upgrade\" and \"downgrade\" functions in your tests to ensure\nconsistent handling regardless of Perl's internal encoding.\n"
                    },
                    {
                        "name": "How do I convert a string to UTF-8?",
                        "content": "If you're mixing UTF-8 and non-UTF-8 strings, it is necessary to upgrade the non-UTF-8\nstrings to UTF-8.  If you've got an SV, the easiest way to do this is:\n\nsvutf8upgrade(sv);\n\nHowever, you must not do this, for example:\n\nif (!SvUTF8(left))\nsvutf8upgrade(left);\n\nIf you do this in a binary operator, you will actually change one of the strings that came\ninto the operator, and, while it shouldn't be noticeable by the end user, it can cause\nproblems in deficient code.\n\nInstead, \"bytestoutf8\" will give you a UTF-8-encoded copy of its string argument.  This is\nuseful for having the data available for comparisons and so on, without harming the original\nSV.  There's also \"utf8tobytes\" to go the other way, but naturally, this will fail if the\nstring contains any characters above 255 that can't be represented in a single byte.\n"
                    },
                    {
                        "name": "How do I compare strings?",
                        "content": "\"svcmp\" in perlapi and \"svcmpflags\" in perlapi do a lexigraphic comparison of two SV's,\nand handle UTF-8ness properly.  Note, however, that Unicode specifies a much fancier\nmechanism for collation, available via the Unicode::Collate module.\n\nTo just compare two strings for equality/non-equality, you can just use \"memEQ()\" and\n\"memNE()\" as usual, except the strings must be both UTF-8 or not UTF-8 encoded.\n\nTo compare two strings case-insensitively, use \"foldEQutf8()\" (the strings don't have to\nhave the same UTF-8ness).\n"
                    },
                    {
                        "name": "Is there anything else I need to know?",
                        "content": "Not really.  Just remember these things:\n\n•  There's no way to tell if a \"char *\" or \"U8 *\" string is UTF-8 or not.  But you can tell\nif an SV is to be treated as UTF-8 by calling \"DOUTF8\" on it, after stringifying it with\n\"SvPV\" or a similar macro.  And, you can tell if SV is actually UTF-8 (even if it is not\nto be treated as such) by looking at its \"SvUTF8\" flag (again after stringifying it).\nDon't forget to set the flag if something should be UTF-8.  Treat the flag as part of the\nPV, even though it's not -- if you pass on the PV to somewhere, pass on the flag too.\n\n•  If a string is UTF-8, always use \"utf8touvchrbuf\" to get at the value, unless\n\"UTF8ISINVARIANT(*s)\" in which case you can use *s.\n\n•  When writing a character UV to a UTF-8 string, always use \"uvchrtoutf8\", unless\n\"UVCHRISINVARIANT(uv))\" in which case you can use \"*s = uv\".\n\n•  Mixing UTF-8 and non-UTF-8 strings is tricky.  Use \"bytestoutf8\" to get a new string\nwhich is UTF-8 encoded, and then combine them.\n"
                    },
                    {
                        "name": "Custom Operators",
                        "content": "Custom operator support is an experimental feature that allows you to define your own ops.\nThis is primarily to allow the building of interpreters for other languages in the Perl core,\nbut it also allows optimizations through the creation of \"macro-ops\" (ops which perform the\nfunctions of multiple ops which are usually executed together, such as \"gvsv, gvsv, add\".)\n\nThis feature is implemented as a new op type, \"OPCUSTOM\".  The Perl core does not \"know\"\nanything special about this op type, and so it will not be involved in any optimizations.\nThis also means that you can define your custom ops to be any op structure -- unary, binary,\nlist and so on -- you like.\n\nIt's important to know what custom operators won't do for you.  They won't let you add new\nsyntax to Perl, directly.  They won't even let you add new keywords, directly.  In fact, they\nwon't change the way Perl compiles a program at all.  You have to do those changes yourself,\nafter Perl has compiled the program.  You do this either by manipulating the op tree using a\n\"CHECK\" block and the \"B::Generate\" module, or by adding a custom peephole optimizer with the\n\"optimize\" module.\n\nWhen you do this, you replace ordinary Perl ops with custom ops by creating ops with the type\n\"OPCUSTOM\" and the \"opppaddr\" of your own PP function.  This should be defined in XS code,\nand should look like the PP ops in \"pp*.c\".  You are responsible for ensuring that your op\ntakes the appropriate number of values from the stack, and you are responsible for adding\nstack marks if necessary.\n\nYou should also \"register\" your op with the Perl interpreter so that it can produce sensible\nerror and warning messages.  Since it is possible to have multiple custom ops within the one\n\"logical\" op type \"OPCUSTOM\", Perl uses the value of \"o->opppaddr\" to determine which\ncustom op it is dealing with.  You should create an \"XOP\" structure for each ppaddr you use,\nset the properties of the custom op with \"XopENTRYset\", and register the structure against\nthe ppaddr using \"Perlcustomopregister\".  A trivial example might look like:\n\nstatic XOP myxop;\nstatic OP *mypp(pTHX);\n\nBOOT:\nXopENTRYset(&myxop, xopname, \"myxop\");\nXopENTRYset(&myxop, xopdesc, \"Useless custom op\");\nPerlcustomopregister(aTHX mypp, &myxop);\n\nThe available fields in the structure are:\n\nxopname\nA short name for your op.  This will be included in some error messages, and will also be\nreturned as \"$op->name\" by the B module, so it will appear in the output of module like\nB::Concise.\n\nxopdesc\nA short description of the function of the op.\n\nxopclass\nWhich of the various *OP structures this op uses.  This should be one of the \"OA*\"\nconstants from op.h, namely\n\nOABASEOP\nOAUNOP\nOABINOP\nOALOGOP\nOALISTOP\nOAPMOP\nOASVOP\nOAPADOP\nOAPVOPORSVOP\nThis should be interpreted as '\"PVOP\"' only.  The \"ORSVOP\" is because the only core\n\"PVOP\", \"OPTRANS\", can sometimes be a \"SVOP\" instead.\n\nOALOOP\nOACOP\n\nThe other \"OA*\" constants should not be used.\n\nxoppeep\nThis member is of type \"Perlcpeept\", which expands to \"void (*Perlcpeept)(aTHX OP\n*o, OP *oldop)\".  If it is set, this function will be called from \"Perlrpeep\" when ops\nof this type are encountered by the peephole optimizer.  o is the OP that needs\noptimizing; oldop is the previous OP optimized, whose \"opnext\" points to o.\n\n\"B::Generate\" directly supports the creation of custom ops by name.\n"
                    }
                ]
            },
            "Stacks": {
                "content": "Descriptions above occasionally refer to \"the stack\", but there are in fact many stack-like\ndata structures within the perl interpreter. When otherwise unqualified, \"the stack\" usually\nrefers to the value stack.\n\nThe various stacks have different purposes, and operate in slightly different ways. Their\ndifferences are noted below.\n",
                "subsections": [
                    {
                        "name": "Value Stack",
                        "content": "This stack stores the values that regular perl code is operating on, usually intermediate\nvalues of expressions within a statement. The stack itself is formed of an array of SV\npointers.\n\nThe base of this stack is pointed to by the interpreter variable \"PLstackbase\", of type \"SV\n\".\n\nThe head of the stack is \"PLstacksp\", and points to the most recently-pushed item.\n\nItems are pushed to the stack by using the \"PUSHs()\" macro or its variants described above;\n\"XPUSHs()\", \"mPUSHs()\", \"mXPUSHs()\" and the typed versions. Note carefully that the non-\"X\"\nversions of these macros do not check the size of the stack and assume it to be big enough.\nThese must be paired with a suitable check of the stack's size, such as the \"EXTEND\" macro to\nensure it is large enough. For example\n\nEXTEND(SP, 4);\nmPUSHi(10);\nmPUSHi(20);\nmPUSHi(30);\nmPUSHi(40);\n\nThis is slightly more performant than making four separate checks in four separate\n\"mXPUSHi()\" calls.\n\nAs a further performance optimisation, the various \"PUSH\" macros all operate using a local\nvariable \"SP\", rather than the interpreter-global variable \"PLstacksp\". This variable is\ndeclared by the \"dSP\" macro - though it is normally implied by XSUBs and similar so it is\nrare you have to consider it directly. Once declared, the \"PUSH\" macros will operate only on\nthis local variable, so before invoking any other perl core functions you must use the\n\"PUTBACK\" macro to return the value from the local \"SP\" variable back to the interpreter\nvariable. Similarly, after calling a perl core function which may have had reason to move the\nstack or push/pop values to it, you must use the \"SPAGAIN\" macro which refreshes the local\n\"SP\" value back from the interpreter one.\n\nItems are popped from the stack by using the \"POPs\" macro or its typed versions, There is\nalso a macro \"TOPs\" that inspects the topmost item without removing it.\n\nNote specifically that SV pointers on the value stack do not contribute to the overall\nreference count of the xVs being referred to. If newly-created xVs are being pushed to the\nstack you must arrange for them to be destroyed at a suitable time; usually by using one of\nthe \"mPUSH*\" macros or \"sv2mortal()\" to mortalise the xV.\n"
                    },
                    {
                        "name": "Mark Stack",
                        "content": "The value stack stores individual perl scalar values as temporaries between expressions. Some\nperl expressions operate on entire lists; for that purpose we need to know where on the stack\neach list begins. This is the purpose of the mark stack.\n\nThe mark stack stores integers as I32 values, which are the height of the value stack at the\ntime before the list began; thus the mark itself actually points to the value stack entry one\nbefore the list. The list itself starts at \"mark + 1\".\n\nThe base of this stack is pointed to by the interpreter variable \"PLmarkstack\", of type \"I32\n*\".\n\nThe head of the stack is \"PLmarkstackptr\", and points to the most recently-pushed item.\n\nItems are pushed to the stack by using the \"PUSHMARK()\" macro. Even though the stack itself\nstores (value) stack indices as integers, the \"PUSHMARK\" macro should be given a stack\npointer directly; it will calculate the index offset by comparing to the \"PLstacksp\"\nvariable. Thus almost always the code to perform this is\n\nPUSHMARK(SP);\n\nItems are popped from the stack by the \"POPMARK\" macro. There is also a macro \"TOPMARK\" that\ninspects the topmost item without removing it. These macros return I32 index values directly.\nThere is also the \"dMARK\" macro which declares a new SV double-pointer variable, called\n\"mark\", which points at the marked stack slot; this is the usual macro that C code will use\nwhen operating on lists given on the stack.\n\nAs noted above, the \"mark\" variable itself will point at the most recently pushed value on\nthe value stack before the list begins, and so the list itself starts at \"mark + 1\". The\nvalues of the list may be iterated by code such as\n\nfor(SV svp = mark + 1; svp <= PLstacksp; svp++) {\nSV *item = *svp;\n...\n}\n\nNote specifically in the case that the list is already empty, \"mark\" will equal\n\"PLstacksp\".\n\nBecause the \"mark\" variable is converted to a pointer on the value stack, extra care must be\ntaken if \"EXTEND\" or any of the \"XPUSH\" macros are invoked within the function, because the\nstack may need to be moved to extend it and so the existing pointer will now be invalid. If\nthis may be a problem, a possible solution is to track the mark offset as an integer and\ntrack the mark itself later on after the stack had been moved.\n\nI32 markoff = POPMARK;\n\n...\n\nSP mark = PLstackbase + markoff;\n"
                    },
                    {
                        "name": "Temporaries Stack",
                        "content": "As noted above, xV references on the main value stack do not contribute to the reference\ncount of an xV, and so another mechanism is used to track when temporary values which live on\nthe stack must be released. This is the job of the temporaries stack.\n\nThe temporaries stack stores pointers to xVs whose reference counts will be decremented soon.\n\nThe base of this stack is pointed to by the interpreter variable \"PLtmpsstack\", of type \"SV\n\".\n\nThe head of the stack is indexed by \"PLtmpsix\", an integer which stores the index in the\narray of the most recently-pushed item.\n\nThere is no public API to directly push items to the temporaries stack. Instead, the API\nfunction \"sv2mortal()\" is used to mortalize an xV, adding its address to the temporaries\nstack.\n\nLikewise, there is no public API to read values from the temporaries stack.  Instead, the\nmacros \"SAVETMPS\" and \"FREETMPS\" are used. The \"SAVETMPS\" macro establishes the base levels\nof the temporaries stack, by capturing the current value of \"PLtmpsix\" into \"PLtmpsfloor\"\nand saving the previous value to the save stack. Thereafter, whenever \"FREETMPS\" is invoked\nall of the temporaries that have been pushed since that level are reclaimed.\n\nWhile it is common to see these two macros in pairs within an \"ENTER\"/ \"LEAVE\" pair, it is\nnot necessary to match them. It is permitted to invoke \"FREETMPS\" multiple times since the\nmost recent \"SAVETMPS\"; for example in a loop iterating over elements of a list. While you\ncan invoke \"SAVETMPS\" multiple times within a scope pair, it is unlikely to be useful.\nSubsequent invocations will move the temporaries floor further up, thus effectively trapping\nthe existing temporaries to only be released at the end of the scope.\n"
                    },
                    {
                        "name": "Save Stack",
                        "content": "The save stack is used by perl to implement the \"local\" keyword and other similar behaviours;\nany cleanup operations that need to be performed when leaving the current scope. Items pushed\nto this stack generally capture the current value of some internal variable or state, which\nwill be restored when the scope is unwound due to leaving, \"return\", \"die\", \"goto\" or other\nreasons.\n\nWhereas other perl internal stacks store individual items all of the same type (usually SV\npointers or integers), the items pushed to the save stack are formed of many different types,\nhaving multiple fields to them. For example, the \"SAVEtINT\" type needs to store both the\naddress of the \"int\" variable to restore, and the value to restore it to. This information\ncould have been stored using fields of a \"struct\", but would have to be large enough to store\nthree pointers in the largest case, which would waste a lot of space in most of the smaller\ncases.\n\nInstead, the stack stores information in a variable-length encoding of \"ANY\" structures. The\nfinal value pushed is stored in the \"UV\" field which encodes the kind of item held by the\npreceeding items; the count and types of which will depend on what kind of item is being\nstored. The kind field is pushed last because that will be the first field to be popped when\nunwinding items from the stack.\n\nThe base of this stack is pointed to by the interpreter variable \"PLsavestack\", of type \"ANY\n*\".\n\nThe head of the stack is indexed by \"PLsavestackix\", an integer which stores the index in\nthe array at which the next item should be pushed. (Note that this is different to most other\nstacks, which reference the most recently-pushed item).\n\nItems are pushed to the save stack by using the various \"SAVE...()\" macros.  Many of these\nmacros take a variable and store both its address and current value on the save stack,\nensuring that value gets restored on scope exit.\n\nSAVEI8(i8)\nSAVEI16(i16)\nSAVEI32(i32)\nSAVEINT(i)\n...\n\nThere are also a variety of other special-purpose macros which save particular types or\nvalues of interest. \"SAVETMPS\" has already been mentioned above.  Others include \"SAVEFREEPV\"\nwhich arranges for a PV (i.e. a string buffer) to be freed, or \"SAVEDESTRUCTOR\" which\narranges for a given function pointer to be invoked on scope exit. A full list of such macros\ncan be found in scope.h.\n\nThere is no public API for popping individual values or items from the save stack. Instead,\nvia the scope stack, the \"ENTER\" and \"LEAVE\" pair form a way to start and stop nested scopes.\nLeaving a nested scope via \"LEAVE\" will restore all of the saved values that had been pushed\nsince the most recent \"ENTER\".\n"
                    },
                    {
                        "name": "Scope Stack",
                        "content": "As with the mark stack to the value stack, the scope stack forms a pair with the save stack.\nThe scope stack stores the height of the save stack at which nested scopes begin, and allows\nthe save stack to be unwound back to that point when the scope is left.\n\nWhen perl is built with debugging enabled, there is a second part to this stack storing\nhuman-readable string names describing the type of stack context. Each push operation saves\nthe name as well as the height of the save stack, and each pop operation checks the topmost\nname with what is expected, causing an assertion failure if the name does not match.\n\nThe base of this stack is pointed to by the interpreter variable \"PLscopestack\", of type\n\"I32 *\". If enabled, the scope stack names are stored in a separate array pointed to by\n\"PLscopestackname\", of type \"const char \".\n\nThe head of the stack is indexed by \"PLscopestackix\", an integer which stores the index of\nthe array or arrays at which the next item should be pushed. (Note that this is different to\nmost other stacks, which reference the most recently-pushed item).\n\nValues are pushed to the scope stack using the \"ENTER\" macro, which begins a new nested\nscope. Any items pushed to the save stack are then restored at the next nested invocation of\nthe \"LEAVE\" macro.\n"
                    },
                    {
                        "name": "Dynamic Scope and the Context Stack",
                        "content": "Note: this section describes a non-public internal API that is subject to change without\nnotice.\n"
                    },
                    {
                        "name": "Introduction to the context stack",
                        "content": "In Perl, dynamic scoping refers to the runtime nesting of things like subroutine calls, evals\netc, as well as the entering and exiting of block scopes. For example, the restoring of a\n\"local\"ised variable is determined by the dynamic scope.\n\nPerl tracks the dynamic scope by a data structure called the context stack, which is an array\nof \"PERLCONTEXT\" structures, and which is itself a big union for all the types of context.\nWhenever a new scope is entered (such as a block, a \"for\" loop, or a subroutine call), a new\ncontext entry is pushed onto the stack. Similarly when leaving a block or returning from a\nsubroutine call etc. a context is popped. Since the context stack represents the current\ndynamic scope, it can be searched.  For example, \"next LABEL\" searches back through the stack\nlooking for a loop context that matches the label; \"return\" pops contexts until it finds a\nsub or eval context or similar; \"caller\" examines sub contexts on the stack.\n\nEach context entry is labelled with a context type, \"cxtype\". Typical context types are\n\"CXtSUB\", \"CXtEVAL\" etc., as well as \"CXtBLOCK\" and \"CXtNULL\" which represent a basic\nscope (as pushed by \"ppenter\") and a sort block. The type determines which part of the\ncontext union are valid.\n\nThe main division in the context struct is between a substitution scope (\"CXtSUBST\") and\nblock scopes, which are everything else. The former is just used while executing \"s///e\", and\nwon't be discussed further here.\n\nAll the block scope types share a common base, which corresponds to \"CXtBLOCK\". This stores\nthe old values of various scope-related variables like \"PLcurpm\", as well as information\nabout the current scope, such as \"gimme\". On scope exit, the old variables are restored.\n\nParticular block scope types store extra per-type information. For example, \"CXtSUB\" stores\nthe currently executing CV, while the various for loop types might hold the original loop\nvariable SV. On scope exit, the per-type data is processed; for example the CV has its\nreference count decremented, and the original loop variable is restored.\n\nThe macro \"cxstack\" returns the base of the current context stack, while \"cxstackix\" is the\nindex of the current frame within that stack.\n\nIn fact, the context stack is actually part of a stack-of-stacks system; whenever something\nunusual is done such as calling a \"DESTROY\" or tie handler, a new stack is pushed, then\npopped at the end.\n\nNote that the API described here changed considerably in perl 5.24; prior to that, big macros\nlike \"PUSHBLOCK\" and \"POPSUB\" were used; in 5.24 they were replaced by the inline static\nfunctions described below. In addition, the ordering and detail of how these macros/function\nwork changed in many ways, often subtly. In particular they didn't handle saving the\nsavestack and temps stack positions, and required additional \"ENTER\", \"SAVETMPS\" and \"LEAVE\"\ncompared to the new functions. The old-style macros will not be described further.\n"
                    },
                    {
                        "name": "Pushing contexts",
                        "content": "For pushing a new context, the two basic functions are \"cx = cxpushblock()\", which pushes a\nnew basic context block and returns its address, and a family of similar functions with names\nlike \"cxpushsub(cx)\" which populate the additional type-dependent fields in the \"cx\" struct.\nNote that \"CXtNULL\" and \"CXtBLOCK\" don't have their own push functions, as they don't store\nany data beyond that pushed by \"cxpushblock\".\n\nThe fields of the context struct and the arguments to the \"cx*\" functions are subject to\nchange between perl releases, representing whatever is convenient or efficient for that\nrelease.\n\nA typical context stack pushing can be found in \"ppentersub\"; the following shows a\nsimplified and stripped-down example of a non-XS call, along with comments showing roughly\nwhat each function does.\n\ndMARK;\nU8 gimme      = GIMMEV;\nbool hasargs  = cBOOL(PLop->opflags & OPfSTACKED);\nOP *retop     = PLop->opnext;\nI32 oldssix = PLsavestackix;\nCV *cv        = ....;\n\n/* ... make mortal copies of stack args which are PADTMPs here ... */\n\n/* ... do any additional savestack pushes here ... */\n\n/* Now push a new context entry of type 'CXtSUB'; initially just\n* doing the actions common to all block types: */\n\ncx = cxpushblock(CXtSUB, gimme, MARK, oldssix);\n\n/* this does (approximately):\nCXINC;              /* cxstackix++ (grow if necessary) */\ncx = CXCUR();      /* and get the address of new frame */\ncx->cxtype        = CXtSUB;\ncx->blkgimme      = gimme;\ncx->blkoldsp      = MARK - PLstackbase;\ncx->blkoldsaveix  = oldssix;\ncx->blkoldcop     = PLcurcop;\ncx->blkoldmarksp  = PLmarkstackptr - PLmarkstack;\ncx->blkoldscopesp = PLscopestackix;\ncx->blkoldpm      = PLcurpm;\ncx->blkoldtmpsfloor = PLtmpsfloor;\n\nPLtmpsfloor        = PLtmpsix;\n*/\n\n\n/* then update the new context frame with subroutine-specific info,\n* such as the CV about to be executed: */\n\ncxpushsub(cx, cv, retop, hasargs);\n\n/* this does (approximately):\ncx->blksub.cv          = cv;\ncx->blksub.olddepth    = CvDEPTH(cv);\ncx->blksub.prevcomppad = PLcomppad;\ncx->cxtype            |= (hasargs) ? CXpHASARGS : 0;\ncx->blksub.retop       = retop;\nSvREFCNTincsimplevoidNN(cv);\n*/\n\nNote that \"cxpushblock()\" sets two new floors: for the args stack (to \"MARK\") and the temps\nstack (to \"PLtmpsix\"). While executing at this scope level, every \"nextstate\" (amongst\nothers) will reset the args and tmps stack levels to these floors. Note that since\n\"cxpushblock\" uses the current value of \"PLtmpsix\" rather than it being passed as an arg,\nthis dictates at what point \"cxpushblock\" should be called. In particular, any new mortals\nwhich should be freed only on scope exit (rather than at the next \"nextstate\") should be\ncreated first.\n\nMost callers of \"cxpushblock\" simply set the new args stack floor to the top of the previous\nstack frame, but for \"CXtLOOPLIST\" it stores the items being iterated over on the stack,\nand so sets \"blkoldsp\" to the top of these items instead. Note that, contrary to its name,\n\"blkoldsp\" doesn't always represent the value to restore \"PLstacksp\" to on scope exit.\n\nNote the early capture of \"PLsavestackix\" to \"oldssix\", which is later passed as an arg\nto \"cxpushblock\". In the case of \"ppentersub\", this is because, although most values\nneeding saving are stored in fields of the context struct, an extra value needs saving only\nwhen the debugger is running, and it doesn't make sense to bloat the struct for this rare\ncase. So instead it is saved on the savestack. Since this value gets calculated and saved\nbefore the context is pushed, it is necessary to pass the old value of \"PLsavestackix\" to\n\"cxpushblock\", to ensure that the saved value gets freed during scope exit.  For most users\nof \"cxpushblock\", where nothing needs pushing on the save stack, \"PLsavestackix\" is just\npassed directly as an arg to \"cxpushblock\".\n\nNote that where possible, values should be saved in the context struct rather than on the\nsave stack; it's much faster that way.\n\nNormally \"cxpushblock\" should be immediately followed by the appropriate \"cxpushfoo\", with\nnothing between them; this is because if code in-between could die (e.g. a warning upgraded\nto fatal), then the context stack unwinding code in \"dounwind\" would see (in the example\nabove) a \"CXtSUB\" context frame, but without all the subroutine-specific fields set, and\ncrashes would soon ensue.\n\nWhere the two must be separate, initially set the type to \"CXtNULL\" or \"CXtBLOCK\", and\nlater change it to \"CXtfoo\" when doing the \"cxpushfoo\". This is exactly what \"ppenteriter\"\ndoes, once it's determined which type of loop it's pushing.\n"
                    },
                    {
                        "name": "Popping contexts",
                        "content": "Contexts are popped using \"cxpopsub()\" etc. and \"cxpopblock()\". Note however, that unlike\n\"cxpushblock\", neither of these functions actually decrement the current context stack\nindex; this is done separately using \"CXPOP()\".\n\nThere are two main ways that contexts are popped. During normal execution as scopes are\nexited, functions like \"ppleave\", \"ppleaveloop\" and \"ppleavesub\" process and pop just one\ncontext using \"cxpopfoo\" and \"cxpopblock\". On the other hand, things like \"ppreturn\" and\n\"next\" may have to pop back several scopes until a sub or loop context is found, and\nexceptions (such as \"die\") need to pop back contexts until an eval context is found. Both of\nthese are accomplished by \"dounwind()\", which is capable of processing and popping all\ncontexts above the target one.\n\nHere is a typical example of context popping, as found in \"ppleavesub\" (simplified\nslightly):\n\nU8 gimme;\nPERLCONTEXT *cx;\nSV oldsp;\nOP *retop;\n\ncx = CXCUR();\n\ngimme = cx->blkgimme;\noldsp = PLstackbase + cx->blkoldsp; /* last arg of previous frame */\n\nif (gimme == GVOID)\nPLstacksp = oldsp;\nelse\nleaveadjuststacks(oldsp, oldsp, gimme, 0);\n\nCXLEAVESCOPE(cx);\ncxpopsub(cx);\ncxpopblock(cx);\nretop = cx->blksub.retop;\nCXPOP(cx);\n\nreturn retop;\n\nThe steps above are in a very specific order, designed to be the reverse order of when the\ncontext was pushed. The first thing to do is to copy and/or protect any return arguments and\nfree any temps in the current scope. Scope exits like an rvalue sub normally return a mortal\ncopy of their return args (as opposed to lvalue subs). It is important to make this copy\nbefore the save stack is popped or variables are restored, or bad things like the following\ncan happen:\n\nsub f { my $x =...; $x }  # $x freed before we get to copy it\nsub f { /(...)/;    $1 }  # PLcurpm restored before $1 copied\n\nAlthough we wish to free any temps at the same time, we have to be careful not to free any\ntemps which are keeping return args alive; nor to free the temps we have just created while\nmortal copying return args. Fortunately, \"leaveadjuststacks()\" is capable of making mortal\ncopies of return args, shifting args down the stack, and only processing those entries on the\ntemps stack that are safe to do so.\n\nIn void context no args are returned, so it's more efficient to skip calling\n\"leaveadjuststacks()\". Also in void context, a \"nextstate\" op is likely to be imminently\ncalled which will do a \"FREETMPS\", so there's no need to do that either.\n\nThe next step is to pop savestack entries: \"CXLEAVESCOPE(cx)\" is just defined as\n\"LEAVESCOPE(cx->blkoldsaveix)\". Note that during the popping, it's possible for perl to\ncall destructors, call \"STORE\" to undo localisations of tied vars, and so on. Any of these\ncan die or call \"exit()\". In this case, \"dounwind()\" will be called, and the current context\nstack frame will be re-processed. Thus it is vital that all steps in popping a context are\ndone in such a way to support reentrancy.  The other alternative, of decrementing\n\"cxstackix\" before processing the frame, would lead to leaks and the like if something died\nhalfway through, or overwriting of the current frame.\n\n\"CXLEAVESCOPE\" itself is safely re-entrant: if only half the savestack items have been\npopped before dying and getting trapped by eval, then the \"CXLEAVESCOPE\"s in \"dounwind\" or\n\"ppleaveeval\" will continue where the first one left off.\n\nThe next step is the type-specific context processing; in this case \"cxpopsub\". In part,\nthis looks like:\n\ncv = cx->blksub.cv;\nCvDEPTH(cv) = cx->blksub.olddepth;\ncx->blksub.cv = NULL;\nSvREFCNTdec(cv);\n\nwhere its processing the just-executed CV. Note that before it decrements the CV's reference\ncount, it nulls the \"blksub.cv\". This means that if it re-enters, the CV won't be freed\ntwice. It also means that you can't rely on such type-specific fields having useful values\nafter the return from \"cxpopfoo\".\n\nNext, \"cxpopblock\" restores all the various interpreter vars to their previous values or\nprevious high water marks; it expands to:\n\nPLmarkstackptr = PLmarkstack + cx->blkoldmarksp;\nPLscopestackix = cx->blkoldscopesp;\nPLcurpm         = cx->blkoldpm;\nPLcurcop        = cx->blkoldcop;\nPLtmpsfloor    = cx->blkoldtmpsfloor;\n\nNote that it doesn't restore \"PLstacksp\"; as mentioned earlier, which value to restore it\nto depends on the context type (specifically \"for (list) {}\"), and what args (if any) it\nreturns; and that will already have been sorted out earlier by \"leaveadjuststacks()\".\n\nFinally, the context stack pointer is actually decremented by \"CXPOP(cx)\".  After this\npoint, it's possible that that the current context frame could be overwritten by other\ncontexts being pushed. Although things like ties and \"DESTROY\" are supposed to work within a\nnew context stack, it's best not to assume this. Indeed on debugging builds, \"CXPOP(cx)\"\ndeliberately sets \"cx\" to null to detect code that is still relying on the field values in\nthat context frame. Note in the \"ppleavesub()\" example above, we grab \"blksub.retop\" before\ncalling \"CXPOP\".\n"
                    },
                    {
                        "name": "Redoing contexts",
                        "content": "Finally, there is \"cxtopblock(cx)\", which acts like a super-\"nextstate\" as regards to\nresetting various vars to their base values. It is used in places like \"ppnext\", \"ppredo\"\nand \"ppgoto\" where rather than exiting a scope, we want to re-initialise the scope. As well\nas resetting \"PLstacksp\" like \"nextstate\", it also resets \"PLmarkstackptr\",\n\"PLscopestackix\" and \"PLcurpm\". Note that it doesn't do a \"FREETMPS\".\n"
                    },
                    {
                        "name": "Slab-based operator allocation",
                        "content": "Note: this section describes a non-public internal API that is subject to change without\nnotice.\n\nPerl's internal error-handling mechanisms implement \"die\" (and its internal equivalents)\nusing longjmp. If this occurs during lexing, parsing or compilation, we must ensure that any\nops allocated as part of the compilation process are freed. (Older Perl versions did not\nadequately handle this situation: when failing a parse, they would leak ops that were stored\nin C \"auto\" variables and not linked anywhere else.)\n\nTo handle this situation, Perl uses op slabs that are attached to the currently-compiling CV.\nA slab is a chunk of allocated memory. New ops are allocated as regions of the slab. If the\nslab fills up, a new one is created (and linked from the previous one). When an error occurs\nand the CV is freed, any ops remaining are freed.\n\nEach op is preceded by two pointers: one points to the next op in the slab, and the other\npoints to the slab that owns it. The next-op pointer is needed so that Perl can iterate over\na slab and free all its ops. (Op structures are of different sizes, so the slab's ops can't\nmerely be treated as a dense array.)  The slab pointer is needed for accessing a reference\ncount on the slab: when the last op on a slab is freed, the slab itself is freed.\n\nThe slab allocator puts the ops at the end of the slab first. This will tend to allocate the\nleaves of the op tree first, and the layout will therefore hopefully be cache-friendly. In\naddition, this means that there's no need to store the size of the slab (see below on why\nslabs vary in size), because Perl can follow pointers to find the last op.\n\nIt might seem possible to eliminate slab reference counts altogether, by having all ops\nimplicitly attached to \"PLcompcv\" when allocated and freed when the CV is freed. That would\nalso allow \"opfree\" to skip \"FreeOp\" altogether, and thus free ops faster. But that doesn't\nwork in those cases where ops need to survive beyond their CVs, such as re-evals.\n\nThe CV also has to have a reference count on the slab. Sometimes the first op created is\nimmediately freed. If the reference count of the slab reaches 0, then it will be freed with\nthe CV still pointing to it.\n\nCVs use the \"CVfSLABBED\" flag to indicate that the CV has a reference count on the slab.\nWhen this flag is set, the slab is accessible via \"CvSTART\" when \"CvROOT\" is not set, or by\nsubtracting two pointers \"(2*sizeof(I32 *))\" from \"CvROOT\" when it is set. The alternative to\nthis approach of sneaking the slab into \"CvSTART\" during compilation would be to enlarge the\n\"xpvcv\" struct by another pointer. But that would make all CVs larger, even though slab-based\nop freeing is typically of benefit only for programs that make significant use of string\neval.\n\nWhen the \"CVfSLABBED\" flag is set, the CV takes responsibility for freeing the slab. If\n\"CvROOT\" is not set when the CV is freed or undeffed, it is assumed that a compilation error\nhas occurred, so the op slab is traversed and all the ops are freed.\n\nUnder normal circumstances, the CV forgets about its slab (decrementing the reference count)\nwhen the root is attached. So the slab reference counting that happens when ops are freed\ntakes care of freeing the slab. In some cases, the CV is told to forget about the slab\n(\"cvforgetslab\") precisely so that the ops can survive after the CV is done away with.\n\nForgetting the slab when the root is attached is not strictly necessary, but avoids potential\nproblems with \"CvROOT\" being written over. There is code all over the place, both in core and\non CPAN, that does things with \"CvROOT\", so forgetting the slab makes things more robust and\navoids potential problems.\n\nSince the CV takes ownership of its slab when flagged, that flag is never copied when a CV is\ncloned, as one CV could free a slab that another CV still points to, since forced freeing of\nops ignores the reference count (but asserts that it looks right).\n\nTo avoid slab fragmentation, freed ops are marked as freed and attached to the slab's freed\nchain (an idea stolen from DBM::Deep). Those freed ops are reused when possible. Not reusing\nfreed ops would be simpler, but it would result in significantly higher memory usage for\nprograms with large \"if (DEBUG) {...}\" blocks.\n\n\"SAVEFREEOP\" is slightly problematic under this scheme. Sometimes it can cause an op to be\nfreed after its CV. If the CV has forcibly freed the ops on its slab and the slab itself,\nthen we will be fiddling with a freed slab. Making \"SAVEFREEOP\" a no-op doesn't help, as\nsometimes an op can be savefreed when there is no compilation error, so the op would never be\nfreed. It holds a reference count on the slab, so the whole slab would leak. So \"SAVEFREEOP\"\nnow sets a special flag on the op (\"->opsavefree\"). The forced freeing of ops after a\ncompilation error won't free any ops thus marked.\n\nSince many pieces of code create tiny subroutines consisting of only a few ops, and since a\nhuge slab would be quite a bit of baggage for those to carry around, the first slab is always\nvery small. To avoid allocating too many slabs for a single CV, each subsequent slab is twice\nthe size of the previous.\n\nSmartmatch expects to be able to allocate an op at run time, run it, and then throw it away.\nFor that to work the op is simply malloced when PLcompcv hasn't been set up. So all slab-\nallocated ops are marked as such (\"->opslabbed\"), to distinguish them from malloced ops.\n"
                    }
                ]
            },
            "AUTHORS": {
                "content": "Until May 1997, this document was maintained by Jeff Okamoto <okamoto@corp.hp.com>.  It is\nnow maintained as part of Perl itself by the Perl 5 Porters <perl5-porters@perl.org>.\n\nWith lots of help and suggestions from Dean Roehrich, Malcolm Beattie, Andreas Koenig, Paul\nHudson, Ilya Zakharevich, Paul Marquess, Neil Bowers, Matthew Green, Tim Bunce, Spider\nBoardman, Ulrich Pfeifer, Stephen McCamant, and Gurusamy Sarathy.\n",
                "subsections": []
            },
            "SEE ALSO": {
                "content": "perlapi, perlintern, perlxs, perlembed\n\n\n\nperl v5.34.0                                 2025-07-25                                  PERLGUTS(1)",
                "subsections": []
            }
        }
    }
}