{
    "mode": "man",
    "parameter": "perliol",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perliol/1/json",
    "generated": "2026-08-21T23:17:27Z",
    "synopsis": "/* Defining a layer ... */\n#include <perliol.h>",
    "sections": {
        "NAME": {
            "content": "perliol - C API for Perl's implementation of IO in Layers.\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "/* Defining a layer ... */\n#include <perliol.h>\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This document describes the behavior and implementation of the PerlIO abstraction described\nin perlapio when \"USEPERLIO\" is defined.\n",
            "subsections": [
                {
                    "name": "History and Background",
                    "content": "The PerlIO abstraction was introduced in perl5.00302 but languished as just an abstraction\nuntil perl5.7.0. However during that time a number of perl extensions switched to using it,\nso the API is mostly fixed to maintain (source) compatibility.\n\nThe aim of the implementation is to provide the PerlIO API in a flexible and platform neutral\nmanner. It is also a trial of an \"Object Oriented C, with vtables\" approach which may be\napplied to Raku.\n"
                },
                {
                    "name": "Basic Structure",
                    "content": "PerlIO is a stack of layers.\n\nThe low levels of the stack work with the low-level operating system calls (file descriptors\nin C) getting bytes in and out, the higher layers of the stack buffer, filter, and otherwise\nmanipulate the I/O, and return characters (or bytes) to Perl.  Terms above and below are used\nto refer to the relative positioning of the stack layers.\n\nA layer contains a \"vtable\", the table of I/O operations (at C level a table of function\npointers), and status flags.  The functions in the vtable implement operations like \"open\",\n\"read\", and \"write\".\n\nWhen I/O, for example \"read\", is requested, the request goes from Perl first down the stack\nusing \"read\" functions of each layer, then at the bottom the input is requested from the\noperating system services, then the result is returned up the stack, finally being\ninterpreted as Perl data.\n\nThe requests do not necessarily go always all the way down to the operating system: that's\nwhere PerlIO buffering comes into play.\n\nWhen you do an open() and specify extra PerlIO layers to be deployed, the layers you specify\nare \"pushed\" on top of the already existing default stack.  One way to see it is that\n\"operating system is on the left\" and \"Perl is on the right\".\n\nWhat exact layers are in this default stack depends on a lot of things: your operating\nsystem, Perl version, Perl compile time configuration, and Perl runtime configuration.  See\nPerlIO, \"PERLIO\" in perlrun, and open for more information.\n\nbinmode() operates similarly to open(): by default the specified layers are pushed on top of\nthe existing stack.\n\nHowever, note that even as the specified layers are \"pushed on top\" for open() and binmode(),\nthis doesn't mean that the effects are limited to the \"top\": PerlIO layers can be very\n'active' and inspect and affect layers also deeper in the stack.  As an example there is a\nlayer called \"raw\" which repeatedly \"pops\" layers until it reaches the first layer that has\ndeclared itself capable of handling binary data.  The \"pushed\" layers are processed in left-\nto-right order.\n\nsysopen() operates (unsurprisingly) at a lower level in the stack than open().  For example\nin Unix or Unix-like systems sysopen() operates directly at the level of file descriptors: in\nthe terms of PerlIO layers, it uses only the \"unix\" layer, which is a rather thin wrapper on\ntop of the Unix file descriptors.\n"
                },
                {
                    "name": "Layers vs Disciplines",
                    "content": "Initial discussion of the ability to modify IO streams behaviour used the term \"discipline\"\nfor the entities which were added. This came (I believe) from the use of the term in \"sfio\",\nwhich in turn borrowed it from \"line disciplines\" on Unix terminals. However, this document\n(and the C code) uses the term \"layer\".\n\nThis is, I hope, a natural term given the implementation, and should avoid connotations that\nare inherent in earlier uses of \"discipline\" for things which are rather different.\n"
                },
                {
                    "name": "Data Structures",
                    "content": "The basic data structure is a PerlIOl:\n\ntypedef struct PerlIO PerlIOl;\ntypedef struct PerlIOfuncs PerlIOfuncs;\ntypedef PerlIOl *PerlIO;\n\nstruct PerlIO\n{\nPerlIOl *      next;       /* Lower layer */\nPerlIOfuncs * tab;        /* Functions for this layer */\nU32            flags;      /* Various flags for state */\n};\n\nA \"PerlIOl *\" is a pointer to the struct, and the application level \"PerlIO *\" is a pointer\nto a \"PerlIOl *\" - i.e. a pointer to a pointer to the struct. This allows the application\nlevel \"PerlIO *\" to remain constant while the actual \"PerlIOl *\" underneath changes. (Compare\nperl's \"SV *\" which remains constant while its \"svany\" field changes as the scalar's type\nchanges.) An IO stream is then in general represented as a pointer to this linked-list of\n\"layers\".\n\nIt should be noted that because of the double indirection in a \"PerlIO *\", a\n\"&(perlio->next)\" \"is\" a \"PerlIO *\", and so to some degree at least one layer can use the\n\"standard\" API on the next layer down.\n\nA \"layer\" is composed of two parts:\n\n1.  The functions and attributes of the \"layer class\".\n\n2.  The per-instance data for a particular handle.\n"
                },
                {
                    "name": "Functions and Attributes",
                    "content": "The  functions and attributes are accessed via the \"tab\" (for table) member of \"PerlIOl\". The\nfunctions (methods of the layer \"class\") are fixed, and are  defined  by  the  \"PerlIOfuncs\"\ntype. They are broadly the same as the public \"PerlIOxxxxx\" functions:\n\nstruct PerlIOfuncs\n{\nSizet     fsize;\nchar *     name;\nSizet     size;\nIV         kind;\nIV         (*Pushed)(pTHX PerlIO *f,\nconst char *mode,\nSV *arg,\nPerlIOfuncs *tab);\nIV         (*Popped)(pTHX PerlIO *f);\nPerlIO *   (*Open)(pTHX PerlIOfuncs *tab,\nPerlIOlistt *layers, IV n,\nconst char *mode,\nint fd, int imode, int perm,\nPerlIO *old,\nint narg, SV args);\nIV         (*Binmode)(pTHX PerlIO *f);\nSV *       (*Getarg)(pTHX PerlIO *f, CLONEPARAMS *param, int flags)\nIV         (*Fileno)(pTHX PerlIO *f);\nPerlIO *   (*Dup)(pTHX PerlIO *f,\nPerlIO *o,\nCLONEPARAMS *param,\nint flags)\n/* Unix-like functions - cf sfio line disciplines */\nSSizet    (*Read)(pTHX PerlIO *f, void *vbuf, Sizet count);\nSSizet    (*Unread)(pTHX PerlIO *f, const void *vbuf, Sizet count);\nSSizet    (*Write)(pTHX PerlIO *f, const void *vbuf, Sizet count);\nIV         (*Seek)(pTHX PerlIO *f, Offt offset, int whence);\nOfft      (*Tell)(pTHX PerlIO *f);\nIV         (*Close)(pTHX PerlIO *f);\n/* Stdio-like buffered IO functions */\nIV         (*Flush)(pTHX PerlIO *f);\nIV         (*Fill)(pTHX PerlIO *f);\nIV         (*Eof)(pTHX PerlIO *f);\nIV         (*Error)(pTHX PerlIO *f);\nvoid       (*Clearerr)(pTHX PerlIO *f);\nvoid       (*Setlinebuf)(pTHX PerlIO *f);\n/* Perl's snooping functions */\nSTDCHAR *  (*Getbase)(pTHX PerlIO *f);\nSizet     (*Getbufsiz)(pTHX PerlIO *f);\nSTDCHAR *  (*Getptr)(pTHX PerlIO *f);\nSSizet    (*Getcnt)(pTHX PerlIO *f);\nvoid       (*Setptrcnt)(pTHX PerlIO *f,STDCHAR *ptr,SSizet cnt);\n};\n\nThe first few members of the struct give a function table size for compatibility check \"name\"\nfor  the  layer,  the   size  to \"malloc\" for the per-instance data, and some flags which are\nattributes of the class as whole (such as whether it is a buffering layer), then  follow  the\nfunctions which fall into four basic groups:\n\n1.  Opening and setup functions\n\n2.  Basic IO operations\n\n3.  Stdio class buffering options.\n\n4.  Functions to support Perl's traditional \"fast\" access to the buffer.\n\nA  layer does not have to implement all the functions, but the whole table has to be present.\nUnimplemented slots can be NULL (which will result in an error when called) or can be  filled\nin with stubs to \"inherit\" behaviour from a \"base class\". This \"inheritance\" is fixed for all\ninstances  of  the layer, but as the layer chooses which stubs to populate the table, limited\n\"multiple inheritance\" is possible.\n"
                },
                {
                    "name": "Per-instance Data",
                    "content": "The per-instance data are held in memory beyond the basic PerlIOl struct, by making a PerlIOl\nthe first member of the layer's struct thus:\n\ntypedef struct\n{\nstruct PerlIO base;       /* Base \"class\" info */\nSTDCHAR *      buf;        /* Start of buffer */\nSTDCHAR *      end;        /* End of valid part of buffer */\nSTDCHAR *      ptr;        /* Current position in buffer */\nOfft          posn;       /* Offset of buf into the file */\nSizet         bufsiz;     /* Real size of buffer */\nIV             oneword;    /* Emergency buffer */\n} PerlIOBuf;\n\nIn this way (as for perl's scalars) a pointer to a PerlIOBuf can be treated as a pointer to a\nPerlIOl.\n"
                },
                {
                    "name": "Layers in action.",
                    "content": "table           perlio          unix\n|           |\n+-----------+    +----------+    +--------+\nPerlIO ->|           |--->|  next    |--->|  NULL  |\n+-----------+    +----------+    +--------+\n|           |    |  buffer  |    |   fd   |\n+-----------+    |          |    +--------+\n|           |    +----------+\n\nThe above attempts to show how the layer scheme works in a simple  case.   The  application's\n\"PerlIO  *\"  points  to  an  entry in the table(s) representing open (allocated) handles. For\nexample the first three slots in the table correspond to \"stdin\",\"stdout\" and  \"stderr\".  The\ntable  in turn points to the current \"top\" layer for the handle - in this case an instance of\nthe generic buffering layer \"perlio\". That layer in turn points to the next layer down  -  in\nthis case the low-level \"unix\" layer.\n\nThe above is roughly equivalent to a \"stdio\" buffered stream, but with much more flexibility:\n\n•   If Unix level \"read\"/\"write\"/\"lseek\" is not appropriate for (say) sockets then the \"unix\"\nlayer can be replaced (at open time or even dynamically) with a \"socket\" layer.\n\n•   Different  handles  can  have  different  buffering schemes. The \"top\" layer could be the\n\"mmap\" layer if reading disk files was quicker using \"mmap\" than \"read\". An  \"unbuffered\"\nstream can be implemented simply by not having a buffer layer.\n\n•   Extra  layers  can  be  inserted  to  process the data as it flows through.  This was the\ndriving need for including the scheme in perl 5.7.0+ - we needed  a  mechanism  to  allow\ndata  to be translated between perl's internal encoding (conceptually at least Unicode as\nUTF-8),  and  the  \"native\"  format  used  by  the  system.  This  is  provided  by   the\n\":encoding(xxxx)\" layer which typically sits above the buffering layer.\n\n•   A  layer  can  be added that does \"\\n\" to CRLF translation. This layer can be used on any\nplatform, not just those that normally do such things.\n"
                },
                {
                    "name": "Per-instance flag bits",
                    "content": "The generic flag bits are a hybrid of \"OXXXXX\" style flags  deduced  from  the  mode  string\npassed to PerlIOopen(), and state bits for typical buffer layers.\n\nPERLIOFEOF\nEnd of file.\n\nPERLIOFCANWRITE\nWrites are permitted, i.e. opened as \"w\" or \"r+\" or \"a\", etc.\n\nPERLIOFCANREAD\nReads are permitted i.e. opened \"r\" or \"w+\" (or even \"a+\" - ick).\n\nPERLIOFERROR\nAn error has occurred (for PerlIOerror()).\n\nPERLIOFTRUNCATE\nTruncate file suggested by open mode.\n\nPERLIOFAPPEND\nAll writes should be appends.\n\nPERLIOFCRLF\nLayer  is  performing Win32-like \"\\n\" mapped to CR,LF for output and CR,LF mapped to \"\\n\"\nfor input. Normally the provided \"crlf\" layer is the only layer that  need  bother  about\nthis.  PerlIObinmode()  will  mess  with  this flag rather than add/remove layers if the\n\"PERLIOKCANCRLF\" bit is set for the layers class.\n\nPERLIOFUTF8\nData written to this layer should be UTF-8 encoded; data provided by this layer should be\nconsidered UTF-8 encoded. Can be set on any layer by \":utf8\" dummy  layer.  Also  set  on\n\":encoding\" layer.\n\nPERLIOFUNBUF\nLayer  is  unbuffered - i.e. write to next layer down should occur for each write to this\nlayer.\n\nPERLIOFWRBUF\nThe buffer for this layer currently holds data written to it but not sent to next layer.\n\nPERLIOFRDBUF\nThe buffer for this layer currently holds unconsumed data read from layer below.\n\nPERLIOFLINEBUF\nLayer is line buffered. Write data should be passed to next layer down whenever a \"\\n\" is\nseen. Any data beyond the \"\\n\" should then be processed.\n\nPERLIOFTEMP\nFile has been unlink()ed, or should be deleted on close().\n\nPERLIOFOPEN\nHandle is open.\n\nPERLIOFFASTGETS\nThis instance of this layer supports the \"fast \"gets\"\" interface.  Normally set based  on\n\"PERLIOKFASTGETS\"  for  the class and by the existence of the function(s) in the table.\nHowever a class that normally  provides  that  interface  may  need  to  avoid  it  on  a\nparticular instance. The \"pending\" layer needs to do this when it is pushed above a layer\nwhich does not support the interface.  (Perl's svgets() does not expect the streams fast\n\"gets\" behaviour to change during one \"get\".)\n"
                },
                {
                    "name": "Methods in Detail",
                    "content": "fsize\nSizet fsize;\n\nSize  of  the function table. This is compared against the value PerlIO code \"knows\" as a\ncompatibility check. Future versions may be able to tolerate layers compiled  against  an\nold version of the headers.\n\nname\nchar * name;\n\nThe  name  of the layer whose open() method Perl should invoke on open().  For example if\nthe layer is called APR, you will call:\n\nopen $fh, \">:APR\", ...\n\nand Perl knows that it has to invoke the PerlIOAPRopen() method implemented by  the  APR\nlayer.\n\nsize\nSizet size;\n\nThe size of the per-instance data structure, e.g.:\n\nsizeof(PerlIOAPR)\n\nIf  this  field is zero then \"PerlIOpushed\" does not malloc anything and assumes layer's\nPushed function will do any required layer stack manipulation - used to avoid malloc/free\noverhead for dummy layers.  If the field is non-zero it must be  at  least  the  size  of\n\"PerlIOl\",  \"PerlIOpushed\" will allocate memory for the layer's data structures and link\nnew layer onto the stream's stack.  (If  the  layer's  Pushed  method  returns  an  error\nindication the layer is popped again.)\n\nkind\nIV kind;\n\n•   PERLIOKBUFFERED\n\nThe layer is buffered.\n\n•   PERLIOKRAW\n\nThe  layer  is  acceptable to have in a binmode(FH) stack - i.e. it does not (or will\nconfigure itself not to) transform bytes passing through it.\n\n•   PERLIOKCANCRLF\n\nLayer can translate between \"\\n\" and CRLF line ends.\n\n•   PERLIOKFASTGETS\n\nLayer allows buffer snooping.\n\n•   PERLIOKMULTIARG\n\nUsed when the layer's open() accepts more arguments than usual. The  extra  arguments\nshould  come  not  before  the \"MODE\" argument. When this flag is used it's up to the\nlayer to validate the args.\n\nPushed\nIV     (*Pushed)(pTHX PerlIO *f,const char *mode, SV *arg);\n\nThe only absolutely mandatory method. Called when the layer is  pushed  onto  the  stack.\nThe \"mode\" argument may be NULL if this occurs post-open. The \"arg\" will be non-\"NULL\" if\nan  argument  string  was  passed.  In most cases this should call PerlIOBasepushed() to\nconvert \"mode\" into the appropriate \"PERLIOFXXXXX\" flags in addition to any actions the\nlayer itself takes.  If a layer is not expecting an argument it need neither save the one\npassed to it, nor provide Getarg() (it could perhaps \"Perlwarn\" that  the  argument  was\nun-expected).\n\nReturns 0 on success. On failure returns -1 and should set errno.\n\nPopped\nIV      (*Popped)(pTHX PerlIO *f);\n\nCalled  when  the  layer  is popped from the stack. A layer will normally be popped after\nClose() is called. But a layer can be popped without  being  closed  if  the  program  is\ndynamically  managing  layers  on  the  stream.  In  such  cases Popped() should free any\nresources (buffers, translation tables, ...) not held directly in the layer's struct.  It\nshould also Unread() any unconsumed data that has been read and buffered from  the  layer\nbelow back to that layer, so that it can be re-provided to what ever is now above.\n\nReturns  0  on  success and failure.  If Popped() returns true then perlio.c assumes that\neither the layer has popped itself, or the  layer  is  super  special  and  needs  to  be\nretained for other reasons.  In most cases it should return false.\n\nOpen\nPerlIO *        (*Open)(...);\n\nThe  Open()  method  has  lots  of  arguments because it combines the functions of perl's\n\"open\", \"PerlIOopen\", perl's \"sysopen\", \"PerlIOfdopen\" and \"PerlIOreopen\".   The  full\nprototype is as follows:\n\nPerlIO *       (*Open)(pTHX PerlIOfuncs *tab,\nPerlIOlistt *layers, IV n,\nconst char *mode,\nint fd, int imode, int perm,\nPerlIO *old,\nint narg, SV args);\n\nOpen  should  (perhaps indirectly) call PerlIOallocate() to allocate a slot in the table\nand  associate  it  with  the  layers  information  for  the  opened  file,  by   calling\n\"PerlIOpush\".  The layers is an array of all the layers destined for the \"PerlIO *\", and\nany  arguments  passed to them, n is the index into that array of the layer being called.\nThe macro \"PerlIOArg\" will return a (possibly \"NULL\") SV * for the argument passed to the\nlayer.\n\nWhere a layer opens or takes ownership of a file descriptor, that  layer  is  responsible\nfor  getting  the  file descriptor's close-on-exec flag into the correct state.  The flag\nshould be clear for a file descriptor numbered less than or equal to  \"PLmaxsysfd\",  and\nset for any file descriptor numbered higher.  For thread safety, when a layer opens a new\nfile descriptor it should if possible open it with the close-on-exec flag initially set.\n\nThe  mode  string  is  an  \"fopen()-like\" string which would match the regular expression\n\"/^[I#]?[rwa]\\+?[bt]?$/\".\n\nThe 'I' prefix is used during creation of \"stdin\"..\"stderr\" via  special  \"PerlIOfdopen\"\ncalls;  the  '#'  prefix  means  that this is \"sysopen\" and that imode and perm should be\npassed to \"PerlLIOopen3\"; 'r' means read, 'w' means write and 'a' means append. The  '+'\nsuffix means that both reading and writing/appending are permitted.  The 'b' suffix means\nfile  should  be binary, and 't' means it is text. (Almost all layers should do the IO in\nbinary mode, and ignore the b/t bits. The \":crlf\" layer should be pushed  to  handle  the\ndistinction.)\n\nIf old is not \"NULL\" then this is a \"PerlIOreopen\". Perl itself does not use this (yet?)\nand semantics are a little vague.\n\nIf  fd  not  negative  then it is the numeric file descriptor fd, which will be open in a\nmanner compatible with  the  supplied  mode  string,  the  call  is  thus  equivalent  to\n\"PerlIOfdopen\".  In  this  case  nargs  will  be zero.  The file descriptor may have the\nclose-on-exec flag either set or clear; it is the responsibility of the layer that  takes\nownership of it to get the flag into the correct state.\n\nIf  nargs  is  greater  than zero then it gives the number of arguments passed to \"open\",\notherwise it will be 1  if  for  example  \"PerlIOopen\"  was  called.   In  simple  cases\nSvPVnolen(*args) is the pathname to open.\n\nIf  a  layer provides Open() it should normally call the Open() method of next layer down\n(if any) and then push itself on top if that succeeds.  \"PerlIOBaseopen\" is provided  to\ndo  exactly  that,  so  in most cases you don't have to write your own Open() method.  If\nthis method is not defined, other layers may have difficulty pushing themselves on top of\nit during open.\n\nIf \"PerlIOpush\" was performed and open has failed, it must \"PerlIOpop\" itself, since if\nit's not, the layer won't be removed and may cause bad problems.\n\nReturns \"NULL\" on failure.\n\nBinmode\nIV        (*Binmode)(pTHX PerlIO *f);\n\nOptional. Used when \":raw\" layer is pushed (explicitly or as a result of binmode(FH)). If\nnot present layer will be popped. If present should configure layer  as  binary  (or  pop\nitself) and return 0.  If it returns -1 for error \"binmode\" will fail with layer still on\nthe stack.\n\nGetarg\nSV *      (*Getarg)(pTHX PerlIO *f,\nCLONEPARAMS *param, int flags);\n\nOptional. If present should return an SV * representing the string argument passed to the\nlayer  when  it  was  pushed.  e.g.  \":encoding(ascii)\"  would  return an SvPV with value\n\"ascii\". (param and flags arguments can be ignored in most cases)\n\n\"Dup\" uses \"Getarg\" to retrieve the argument originally passed to \"Pushed\", so  you  must\nimplement  this function if your layer has an extra argument to \"Pushed\" and will ever be\n\"Dup\"ed.\n\nFileno\nIV        (*Fileno)(pTHX PerlIO *f);\n\nReturns   the   Unix/Posix   numeric   file   descriptor   for   the   handle.   Normally\nPerlIOBasefileno() (which just asks next layer down) will suffice for this.\n\nReturns  -1  on  error,  which  is  considered to include the case where the layer cannot\nprovide such a file descriptor.\n\nDup\nPerlIO * (*Dup)(pTHX PerlIO *f, PerlIO *o,\nCLONEPARAMS *param, int flags);\n\nXXX: Needs more docs.\n\nUsed as part of the \"clone\" process when a thread is spawned (in which case param will be\nnon-NULL) and when a stream is being duplicated via '&' in the \"open\".\n\nSimilar to \"Open\", returns PerlIO* on success, \"NULL\" on failure.\n\nRead\nSSizet (*Read)(pTHX PerlIO *f, void *vbuf, Sizet count);\n\nBasic read operation.\n\nTypically  will  call  \"Fill\"  and  manipulate   pointers   (possibly   via   the   API).\nPerlIOBufread() may be suitable for derived classes which provide \"fast gets\" methods.\n\nReturns actual bytes read, or -1 on an error.\n\nUnread\nSSizet (*Unread)(pTHX PerlIO *f,\nconst void *vbuf, Sizet count);\n\nA  superset  of  stdio's  ungetc().  Should  arrange for future reads to see the bytes in\n\"vbuf\". If there is no obviously better implementation then PerlIOBaseunread()  provides\nthe function by pushing a \"fake\" \"pending\" layer above the calling layer.\n\nReturns the number of unread chars.\n\nWrite\nSSizet (*Write)(PerlIO *f, const void *vbuf, Sizet count);\n\nBasic write operation.\n\nReturns bytes written or -1 on an error.\n\nSeek\nIV      (*Seek)(pTHX PerlIO *f, Offt offset, int whence);\n\nPosition  the  file  pointer.  Should  normally  call its own \"Flush\" method and then the\n\"Seek\" method of next layer down.\n\nReturns 0 on success, -1 on failure.\n\nTell\nOfft   (*Tell)(pTHX PerlIO *f);\n\nReturn the file pointer. May be based on layers  cached  concept  of  position  to  avoid\noverhead.\n\nReturns -1 on failure to get the file pointer.\n\nClose\nIV      (*Close)(pTHX PerlIO *f);\n\nClose  the  stream.  Should  normally  call  PerlIOBaseclose() to flush itself and close\nlayers below, and then deallocate any data structures (buffers, translation tables,  ...)\nnot  held directly in the data structure.\n\nReturns 0 on success, -1 on failure.\n\nFlush\nIV      (*Flush)(pTHX PerlIO *f);\n\nShould make stream's state consistent with layers below. That is, any buffered write data\nshould  be  written,  and file position of lower layers adjusted for data read from below\nbut not actually consumed.  (Should perhaps Unread() such data to the lower layer.)\n\nReturns 0 on success, -1 on failure.\n\nFill\nIV      (*Fill)(pTHX PerlIO *f);\n\nThe buffer for this layer should be  filled  (for  read)  from  layer  below.   When  you\n\"subclass\"  PerlIOBuf layer, you want to use its read method and to supply your own fill\nmethod, which fills the PerlIOBuf's buffer.\n\nReturns 0 on success, -1 on failure.\n\nEof\nIV      (*Eof)(pTHX PerlIO *f);\n\nReturn end-of-file indicator. PerlIOBaseeof() is normally sufficient.\n\nReturns 0 on end-of-file, 1 if not end-of-file, -1 on error.\n\nError\nIV      (*Error)(pTHX PerlIO *f);\n\nReturn error indicator. PerlIOBaseerror() is normally sufficient.\n\nReturns 1 if there is an error (usually when \"PERLIOFERROR\" is set), 0 otherwise.\n\nClearerr\nvoid    (*Clearerr)(pTHX PerlIO *f);\n\nClear end-of-file and error indicators. Should  call  PerlIOBaseclearerr()  to  set  the\n\"PERLIOFXXXXX\" flags, which may suffice.\n\nSetlinebuf\nvoid    (*Setlinebuf)(pTHX PerlIO *f);\n\nMark  the stream as line buffered. PerlIOBasesetlinebuf() sets the PERLIOFLINEBUF flag\nand is normally sufficient.\n\nGetbase\nSTDCHAR *       (*Getbase)(pTHX PerlIO *f);\n\nAllocate (if not already done so) the read buffer for this layer and  return  pointer  to\nit. Return NULL on failure.\n\nGetbufsiz\nSizet  (*Getbufsiz)(pTHX PerlIO *f);\n\nReturn the number of bytes that last Fill() put in the buffer.\n\nGetptr\nSTDCHAR *       (*Getptr)(pTHX PerlIO *f);\n\nReturn the current read pointer relative to this layer's buffer.\n\nGetcnt\nSSizet (*Getcnt)(pTHX PerlIO *f);\n\nReturn the number of bytes left to be read in the current buffer.\n\nSetptrcnt\nvoid    (*Setptrcnt)(pTHX PerlIO *f,\nSTDCHAR *ptr, SSizet cnt);\n\nAdjust  the read pointer and count of bytes to match \"ptr\" and/or \"cnt\".  The application\n(or layer above) must ensure they are consistent.  (Checking is allowed by the paranoid.)\n"
                },
                {
                    "name": "Utilities",
                    "content": "To ask for the next layer down use PerlIONext(PerlIO *f).\n\nTo check that a PerlIO* is valid use PerlIOValid(PerlIO *f).  (All this does is  really  just\nto check that the pointer is non-NULL and that the pointer behind that is non-NULL.)\n\nPerlIOBase(PerlIO *f) returns the \"Base\" pointer, or in other words, the \"PerlIOl*\" pointer.\n\nPerlIOSelf(PerlIO* f, type) return the PerlIOBase cast to a type.\n\nPerlPerlIOorBase(PerlIO*  f, callback, base, failure, args) either calls the callback from\nthe functions of the layer f (just by the name of the IO  function,  like  \"Read\")  with  the\nargs,  or  if there is no such callback, calls the base version of the callback with the same\nargs, or if the f is invalid, set errno to EBADF and return failure.\n\nPerlPerlIOorfail(PerlIO* f, callback, failure, args) either  calls  the  callback  of  the\nfunctions of the layer f with the args, or if there is no such callback, set errno to EINVAL.\nOr if the f is invalid, set errno to EBADF and return failure.\n\nPerlPerlIOorBasevoid(PerlIO*  f,  callback,  base, args) either calls the callback of the\nfunctions of the layer f with the args, or if there is  no  such  callback,  calls  the  base\nversion of the callback with the same args, or if the f is invalid, set errno to EBADF.\n\nPerlPerlIOorfailvoid(PerlIO*  f,  callback,  args)  either  calls  the  callback  of  the\nfunctions of the layer f with the args, or if there is no such callback, set errno to EINVAL.\nOr if the f is invalid, set errno to EBADF.\n"
                },
                {
                    "name": "Implementing PerlIO Layers",
                    "content": "If you find the implementation document unclear or  not  sufficient,  look  at  the  existing\nPerlIO layer implementations, which include:\n\n•   C implementations\n\nThe  perlio.c  and  perliol.h  in  the Perl core implement the \"unix\", \"perlio\", \"stdio\",\n\"crlf\", \"utf8\", \"byte\", \"raw\", \"pending\" layers, and also the \"mmap\" and  \"win32\"  layers\nif  applicable.   (The  \"win32\"  is  currently unfinished and unused, to see what is used\ninstead in Win32, see \"Querying the layers of filehandles\" in PerlIO .)\n\nPerlIO::encoding, PerlIO::scalar, PerlIO::via in the Perl core.\n\nPerlIO::gzip and APR::PerlIO (modperl 2.0) on CPAN.\n\n•   Perl implementations\n\nPerlIO::via::QuotedPrint in the Perl core and PerlIO::via::* on CPAN.\n\nIf you are creating a PerlIO layer, you may want to be lazy, in other words,  implement  only\nthe  methods  that  interest  you.  The other methods you can either replace with the \"blank\"\nmethods\n\nPerlIOBasenoopok\nPerlIOBasenoopfail\n\n(which do nothing, and return zero and -1, respectively)  or  for  certain  methods  you  may\nassume  a  default  behaviour  by using a NULL method.  The Open method looks for help in the\n'parent' layer.  The following table summarizes the behaviour:\n\nmethod      behaviour with NULL\n\nClearerr    PerlIOBaseclearerr\nClose       PerlIOBaseclose\nDup         PerlIOBasedup\nEof         PerlIOBaseeof\nError       PerlIOBaseerror\nFileno      PerlIOBasefileno\nFill        FAILURE\nFlush       SUCCESS\nGetarg      SUCCESS\nGetbase    FAILURE\nGetbufsiz  FAILURE\nGetcnt     FAILURE\nGetptr     FAILURE\nOpen        INHERITED\nPopped      SUCCESS\nPushed      SUCCESS\nRead        PerlIOBaseread\nSeek        FAILURE\nSetcnt     FAILURE\nSetptrcnt  FAILURE\nSetlinebuf  PerlIOBasesetlinebuf\nTell        FAILURE\nUnread      PerlIOBaseunread\nWrite       FAILURE\n\nFAILURE        Set errno (to EINVAL in Unixish, to LIB$INVARG in VMS)\nand return -1 (for numeric return values) or NULL (for\npointers)\nINHERITED      Inherited from the layer below\nSUCCESS        Return 0 (for numeric return values) or a pointer\n"
                },
                {
                    "name": "Core Layers",
                    "content": "The file \"perlio.c\" provides the following layers:\n\n\"unix\"\nA basic non-buffered layer which calls Unix/POSIX read(), write(), lseek(),  close().  No\nbuffering.  Even  on platforms that distinguish between OTEXT and OBINARY this layer is\nalways OBINARY.\n\n\"perlio\"\nA very complete generic buffering layer which provides the whole of  PerlIO  API.  It  is\nalso  intended  to  be  used  as a \"base class\" for other layers. (For example its Read()\nmethod is implemented in terms of the Getcnt()/Getptr()/Setptrcnt() methods).\n\n\"perlio\" over \"unix\" provides a complete replacement for stdio as seen  via  PerlIO  API.\nThis is the default for USEPERLIO when system's stdio does not permit perl's \"fast gets\"\naccess, and which do not distinguish between \"OTEXT\" and \"OBINARY\".\n\n\"stdio\"\nA  layer which provides the PerlIO API via the layer scheme, but implements it by calling\nsystem's stdio. This is (currently) the default if  system's  stdio  provides  sufficient\naccess  to  allow perl's \"fast gets\" access and which do not distinguish between \"OTEXT\"\nand \"OBINARY\".\n\n\"crlf\"\nA layer derived using \"perlio\" as a base class. It  provides  Win32-like  \"\\n\"  to  CR,LF\ntranslation.  Can  either  be applied above \"perlio\" or serve as the buffer layer itself.\n\"crlf\" over \"unix\" is the default if system distinguishes between \"OTEXT\" and \"OBINARY\"\nopens. (At some point \"unix\" will be replaced by  a  \"native\"  Win32  IO  layer  on  that\nplatform,  as  Win32's  read/write  layer  has  various drawbacks.) The \"crlf\" layer is a\nreasonable model for a layer which transforms data in some way.\n\n\"mmap\"\nIf Configure detects mmap() functions this layer is provided (with \"perlio\" as a  \"base\")\nwhich  does  \"read\" operations by mmap()ing the file. Performance improvement is marginal\non modern systems, so it is mainly there as a proof  of  concept.  It  is  likely  to  be\nunbundled  from  the  core  at  some  point. The \"mmap\" layer is a reasonable model for a\nminimalist \"derived\" layer.\n\n\"pending\"\nAn \"internal\" derivative of \"perlio\" which can be used to provide Unread()  function  for\nlayers  which  have no buffer or cannot be bothered.  (Basically this layer's Fill() pops\nitself off the stack and so resumes reading from layer below.)\n\n\"raw\"\nA dummy layer which never exists on the layer stack. Instead when  \"pushed\"  it  actually\npops  the  stack  removing  itself, it then calls Binmode function table entry on all the\nlayers in the stack - normally this (via PerlIOBasebinmode) removes any layers which  do\nnot  have  \"PERLIOKRAW\" bit set. Layers can modify that behaviour by defining their own\nBinmode entry.\n\n\"utf8\"\nAnother dummy layer. When pushed it pops itself and sets the \"PERLIOFUTF8\" flag on  the\nlayer which was (and now is once more) the top of the stack.\n\nIn addition perlio.c also provides a number of PerlIOBasexxxx() functions which are intended\nto  be  used  in  the  table  slots of classes which do not need to do anything special for a\nparticular method.\n"
                },
                {
                    "name": "Extension Layers",
                    "content": "Layers can be made available by extension modules. When an unknown layer is  encountered  the\nPerlIO code will perform the equivalent of :\n\nuse PerlIO 'layer';\n\nWhere layer is the unknown layer. PerlIO.pm will then attempt to:\n\nrequire PerlIO::layer;\n\nIf after that process the layer is still not defined then the \"open\" will fail.\n\nThe following extension layers are bundled with perl:\n\n\":encoding\"\nuse Encoding;\n\nmakes  this  layer  available,  although  PerlIO.pm  \"knows\"  where to find it.  It is an\nexample of a layer which takes an argument as it is called thus:\n\nopen( $fh, \"<:encoding(iso-8859-7)\", $pathname );\n\n\":scalar\"\nProvides support for reading data from and writing data to a scalar.\n\nopen( $fh, \"+<:scalar\", \\$scalar );\n\nWhen a handle is so opened, then reads get bytes from the string value  of  $scalar,  and\nwrites  change the value. In both cases the position in $scalar starts as zero but can be\naltered via \"seek\", and determined via \"tell\".\n\nPlease note that this layer is implied when calling open() thus:\n\nopen( $fh, \"+<\", \\$scalar );\n\n\":via\"\nProvided to allow layers to be implemented as Perl code.  For instance:\n\nuse PerlIO::via::StripHTML;\nopen( my $fh, \"<:via(StripHTML)\", \"index.html\" );\n\nSee PerlIO::via for details.\n"
                }
            ]
        },
        "TODO": {
            "content": "Things that need to be done to improve this document.\n\n•   Explain how to make a valid fh without going through  open()(i.e.  apply  a  layer).  For\nexample if the file is not opened through perl, but we want to get back a fh, like it was\nopened by Perl.\n\nHow PerlIOapplylayera fits in, where its docs, was it made public?\n\nCurrently the example could be something like this:\n\nPerlIO *footoPerlIO(pTHX char *mode, ...)\n{\nchar *mode; /* \"w\", \"r\", etc */\nconst char *layers = \":APR\"; /* the layer name */\nPerlIO *f = PerlIOallocate(aTHX);\nif (!f) {\nreturn NULL;\n}\n\nPerlIOapplylayers(aTHX f, mode, layers);\n\nif (f) {\nPerlIOAPR *st = PerlIOSelf(f, PerlIOAPR);\n/* fill in the st struct, as in open() */\nst->file = file;\nPerlIOBase(f)->flags |= PERLIOFOPEN;\n\nreturn f;\n}\nreturn NULL;\n}\n\n•   fix/add the documentation in places marked as XXX.\n\n•   The  handling  of  errors  by  the  layer  is  not specified. e.g. when $!  should be set\nexplicitly, when the error handling should be just delegated to the top layer.\n\nProbably give some hints on using SETERRNO() or pointers to where they can be found.\n\n•   I think it would help to give some concrete examples to make it easier to understand  the\nAPI.  Of  course  I  agree  that  the API has to be concise, but since there is no second\ndocument that is more of a guide, I think that it'd make it easier to start with the  doc\nwhich  is  an API, but has examples in it in places where things are unclear, to a person\nwho is not a PerlIO guru (yet).\n\nperl v5.38.2                                 2026-06-12                                   PERLIOL(1)",
            "subsections": []
        }
    },
    "summary": "perliol - C API for Perl's implementation of IO in Layers.",
    "flags": [],
    "examples": [],
    "see_also": []
}