PERLIOL(1perl)
π PERLIOL π
okay bestie, so this is perliol β the manual for C API for Perl's implementation of IO in Layers. yes the manpage name is PERLIOL(1perl) but we're not doing a whole intro line about it, we're just diving in, periodt. this is part 1 of 4 so buckle up π
β¨ SYNOPSIS β¨
so if you're defining a layer, you start with this, literally just this:
/* Defining a layer ... */
#include <perliol.h>
that's the whole vibe. movin' on π
πΈ DESCRIPTION πΈ
this doc spills all the tea on how the PerlIO abstraction behaves and how it's implemented β that's the thing described over in perlapio, and it only kicks in when USE_PERLIO is defined. π
π¦ History and Background
okay so story time. the PerlIO abstraction showed up way back in perl5.003_02 and then... kinda just sat there being an abstraction, chillin', not doing much, all the way until perl5.7.0. it's giving "sleeping beauty but make it C". π΄
but bestie, in that whole waiting period a bunch of perl extensions switched over to using it anyway?? so the API is basically frozen now β it's locked in to keep (source) compatibility. no take-backs. π
the actual goal of the implementation is to give you the PerlIO API in a flexible and platform neutral way. also it's a whole experiment in "Object Oriented C, with vtables" β which, fun fact, might get applied to Raku. iconic. π§
π Basic Structure
so, the whole thing: PerlIO is a stack of layers. literally a stack. stacked up.
the low levels of the stack talk to the low-level operating system calls β that's file descriptors in C β and they get bytes in and out. the higher layers buffer, filter, and otherwise mess with the I/O, and hand characters (or bytes) back to Perl.
aboveandbeloware the words we use to talk about where a layer sits relative to the others in the stack. keep that in your pocket, you'll need it. π«Ά
a layer has two things in it:
- a
vtableβ that's the table of I/O operations, which at C level is literally a table of function pointers - status flags
the functions living in the vtable implement stuff like open, read, and write.
when you ask for I/O β say a read β here's the journey: the request goes from Perl down the stack, using the read functions of each layer as it descends. then at the very bottom, the input gets requested from the operating system services. then the result rides back up the stack, and finally it gets interpreted as Perl data. it's a whole round trip bestie βοΈ
but plot twist: requests don't necessarily go all the way down to the operating system every single time β that's exactly where PerlIO buffering comes into play. π
when you do an open() and specify extra PerlIO layers to deploy, the layers you name get "pushed" on top of the default stack that already exists. one way to picture it: "operating system is on the left" and "Perl is on the right". that's the mental model, no cap. π§
which exact layers are in that default stack? depends on so many things: your operating system, your Perl version, Perl compile time configuration, and Perl runtime configuration. if you wanna go deeper, see PerlIO, "PERLIO" in perlrun, and open. π
binmode() operates like open() does: by default, the layers you specify get pushed on top of the existing stack. same energy.
but β IMPORTANT β even though the layers you specify are "pushed on top" for open() and binmode(), that does not mean the effects stay confined to the "top". PerlIO layers can be extremely 'active' β they can inspect and affect layers way deeper in the stack. for example, there's a layer called "raw" that repeatedly "pops" layers until it hits the first layer that declared itself capable of handling binary data. π«£
and the "pushed" layers are processed in left-to-right order.
sysopen() operates (shockingly, not shockingly) at a lower level in the stack than open() does. like, for example on Unix or Unix-like systems, sysopen() works directly at the level of file descriptors. in PerlIO layer terms, it only uses the "unix" layer β which is a pretty thin little wrapper sitting on top of the Unix file descriptors. it's giving minimal effort, and honestly? valid. π
π Layers vs Disciplines
so when people first started talking about being able to modify IO stream behaviour, they used the word "discipline" for these entities being added. where'd that come from? (i believe) it came from its use in "sfio", which borrowed it from "line disciplines" on Unix terminals. a whole lineage. π
but this document (and the C code) uses the term "layer".
and hopefully that's just... the natural term given how it's implemented? and it dodges the connotations baked into the earlier uses of "discipline" for things that are honestly pretty different. so like, we said what we said. π
π Data Structures
the basic data structure is a PerlIOl:
typedef struct _PerlIO PerlIOl;
typedef struct _PerlIO_funcs PerlIO_funcs;
typedef PerlIOl *PerlIO;
struct _PerlIO
{
PerlIOl * next; /* Lower layer */
PerlIO_funcs * tab; /* Functions for this layer */
U32 flags; /* Various flags for state */
};
okay so listen. a "PerlIOl *" is a pointer to the struct. but the application level "PerlIO *" is a pointer to a "PerlIOl *" β meaning, yes, a pointer to a pointer to the struct. double indirection, we love her. β¨
why does that matter? because it lets the application level "PerlIO *" stay constant while the actual "PerlIOl *" underneath it changes. (compare it to perl's "SV *", which stays constant while its "sv_any" field changes as the scalar's type changes. same trick.)
so an IO stream is, in general, represented as a pointer to this linked-list of "layers".
ngl you should note: because of that double indirection in a "PerlIO *", a "&(perlio->next)" "is" a "PerlIO *". which means at least to some degree, one layer can use the "standard" API on the next layer down. it's layers all the way down, bestie. π¦
a "layer" is made of two parts:
- the functions and attributes of the
"layer class". - the per-instance data for a particular handle.
π Functions and Attributes
you get at the functions and attributes through the "tab" (that's short for table) member of PerlIOl. the functions β the methods of the layer's "class" β are fixed, and they're defined by the "PerlIO_funcs" type. broadly speaking they're the same as the public "PerlIO_xxxxx" functions:
struct _PerlIO_funcs
{
Size_t fsize;
char * name;
Size_t size;
IV kind;
IV (*Pushed)(pTHX_ PerlIO *f,
const char *mode,
SV *arg,
PerlIO_funcs *tab);
IV (*Popped)(pTHX_ PerlIO *f);
PerlIO * (*Open)(pTHX_ PerlIO_funcs *tab,
PerlIO_list_t *layers, IV n,
const char *mode,
int fd, int imode, int perm,
PerlIO *old,
int narg, SV **args);
IV (*Binmode)(pTHX_ PerlIO *f);
SV * (*Getarg)(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
IV (*Fileno)(pTHX_ PerlIO *f);
PerlIO * (*Dup)(pTHX_ PerlIO *f,
PerlIO *o,
CLONE_PARAMS *param,
int flags)
/* Unix-like functions - cf sfio line disciplines */
SSize_t (*Read)(pTHX_ PerlIO *f, void *vbuf, Size_t count);
SSize_t (*Unread)(pTHX_ PerlIO *f, const void *vbuf, Size_t count);
SSize_t (*Write)(pTHX_ PerlIO *f, const void *vbuf, Size_t count);
IV (*Seek)(pTHX_ PerlIO *f, Off_t offset, int whence);
Off_t (*Tell)(pTHX_ PerlIO *f);
IV (*Close)(pTHX_ PerlIO *f);
/* Stdio-like buffered IO functions */
IV (*Flush)(pTHX_ PerlIO *f);
IV (*Fill)(pTHX_ PerlIO *f);
IV (*Eof)(pTHX_ PerlIO *f);
IV (*Error)(pTHX_ PerlIO *f);
void (*Clearerr)(pTHX_ PerlIO *f);
void (*Setlinebuf)(pTHX_ PerlIO *f);
/* Perl's snooping functions */
STDCHAR * (*Get_base)(pTHX_ PerlIO *f);
Size_t (*Get_bufsiz)(pTHX_ PerlIO *f);
STDCHAR * (*Get_ptr)(pTHX_ PerlIO *f);
SSize_t (*Get_cnt)(pTHX_ PerlIO *f);
void (*Set_ptrcnt)(pTHX_ PerlIO *f,STDCHAR *ptr,SSize_t cnt);
};
so the first few members of that struct exist to give you:
- a function table size, for the compatibility check
"name"for the layer- the
sizeyou pass to"malloc"for the per-instance data - some flags which are attributes of the class as a whole (like whether it's a buffering layer) π«§
and then come the functions, which fall into four basic groups:
- Opening and setup functions
- Basic IO operations
- Stdio class buffering options.
- Functions to support Perl's traditional "fast" access to the buffer.
a layer does not have to implement all of these functions β but the whole table has to be present. like, you can't skip the table. unimplemented slots can be NULL (which will get you an error when it's called, so... be aware π) or they can be filled in with stubs that "inherit" behaviour from a "base class".
this "inheritance" is fixed for all instances of the layer. but since the layer itself chooses which stubs to populate the table with, limited "multiple inheritance" is possible. we love a flexible queen. π
π§ Per-instance Data
the per-instance data lives in memory beyond the basic PerlIOl struct β and the trick is making a PerlIOl the first member of the layer's struct, like so:
typedef struct
{
struct _PerlIO base; /* Base "class" info */
STDCHAR * buf; /* Start of buffer */
STDCHAR * end; /* End of valid part of buffer */
STDCHAR * ptr; /* Current position in buffer */
Off_t posn; /* Offset of buf into the file */
Size_t bufsiz; /* Real size of buffer */
IV oneword; /* Emergency buffer */
} PerlIOBuf;
and in this way (exactly like perl's scalars) a pointer to a PerlIOBuf can be treated as a pointer to a PerlIOl. it's giving polymorphism but make it C. π
π Layers in action
okay here's the picture, look at it, absorb it:
table perlio unix
| |
+-----------+ +----------+ +--------+
PerlIO ->| |--->| next |--->| NULL |
+-----------+ +----------+ +--------+
| | | buffer | | fd |
+-----------+ | | +--------+
| | +----------+
this is my attempt to show you how the layer scheme works in a simple case. π«Ά
so: the application's "PerlIO *" points to an entry in the table(s) that represent open (allocated) handles. like, the first three slots in that table? those correspond to "stdin", "stdout" and "stderr". the table in turn points to the current "top" layer for the handle β in this case, an instance of the generic buffering layer "perlio". and that layer points to the next layer down β in this case the low-level "unix" layer. chain reaction, but make it IO. π₯
and yeah, the above is roughly equivalent to a "stdio" buffered stream β but with so much more flexibility:
- if Unix level
"read"/"write"/"lseek"is not appropriate for (say) sockets, then you can replace the"unix"layer with a"socket"layer β either at open time or even dynamically. swap her out. π - different handles can have different buffering schemes. the "top" layer could be the
"mmap"layer, if reading disk files was quicker using"mmap"than"read". and an"unbuffered"stream can be implemented simply by not having a buffer layer. no buffer, no problem. β¨ - Extra layers can be inserted to process the data as it flows through. Ngl, this was the whole reason the scheme got added in perl 5.7.0+ β they needed a way to translate data between perl's internal encoding (conceptually at least Unicode as UTF-8) and the "native" format the system uses. That job belongs to the
:encoding(xxxx)layer, which typically sits above the buffering layer. π - A layer can be added that does
"\n"to CRLF translation, and bestie it works on any platform, not just the ones that normally do such things. β¨
π Per-instance flag bits
These generic flag bits are a hybrid situation β part O_XXXXX-style flags deduced from the mode string you hand to PerlIO_open(), and part state bits for typical buffer layers. Both vibes in one field, iconic. π
PERLIO_F_EOFβ End of file, we've hit the wall, nothing left to read. πPERLIO_F_CANWRITEβ Writes are permitted, i.e. opened as"w"or"r+"or"a", etc. βοΈPERLIO_F_CANREADβ Reads are permitted, i.e. opened"r"or"w+"(or even"a+"β ick).PERLIO_F_ERRORβ An error has occurred (forPerlIO_error()). πPERLIO_F_TRUNCATEβ Truncate file suggested by open mode.PERLIO_F_APPENDβ All writes should be appends.PERLIO_F_CRLFβ Layer is performing Win32-like"\n"mapped to CR,LF for output and CR,LF mapped to"\n"for input. Normally the providedcrlflayer is the only layer that need bother about this.PerlIO_binmode()will mess with this flag rather than add/remove layers if thePERLIO_K_CANCRLFbit is set for the layers class.PERLIO_F_UTF8β Data written to this layer should be UTF-8 encoded; data provided by this layer should be considered UTF-8 encoded. Can be set on any layer by the:utf8dummy layer, and it's also set on the:encodinglayer. πPERLIO_F_UNBUFβ Layer is unbuffered β i.e. write to next layer down should occur for each write to this layer.PERLIO_F_WRBUFβ The buffer for this layer currently holds data written to it but not sent to next layer.PERLIO_F_RDBUFβ The buffer for this layer currently holds unconsumed data read from layer below.PERLIO_F_LINEBUFβ Layer is line buffered. Write data should be passed to next layer down whenever a"\n"is seen. Any data beyond the"\n"should then be processed.PERLIO_F_TEMPβ File has beenunlink()ed, or should be deleted onclose().PERLIO_F_OPENβ Handle is open. π«ΆPERLIO_F_FASTGETSβ This instance of this layer supports the"fast "gets""interface. Normally set based onPERLIO_K_FASTGETSfor the class and by the existence of the function(s) in the table. However a class that normally provides that interface may need to avoid it on a particular instance. Thependinglayer needs to do this when it is pushed above a layer which does not support the interface. (Perl'ssv_gets()does not expect the streams fast"gets"behaviour to change during one"get".)
ok so that last one is a lowkey delicate situation β thependinglayer is out here doing damage control so perl'ssv_gets()doesn't get jumpscared mid-"get". π
π§ Methods in Detail
fsize
Size_t fsize;
Size of the function table. This gets compared against the value PerlIO code "knows" as a compatibility check. Future versions may be able to tolerate layers compiled against an old version of the headers. β
name
char * name;
The name of the layer whose open() method Perl should invoke on open(). So like, if the layer is called APR, you will call:
open $fh, ">:APR", ...
and Perl knows it has to invoke the PerlIOAPR_open() method implemented by the APR layer. periodt. π
size
Size_t size;
The size of the per-instance data structure, e.g.:
sizeof(PerlIOAPR)
If this field is zero then PerlIO_pushed does not malloc anything and assumes layer's Pushed function will do any required layer stack manipulation β used to avoid malloc/free overhead for dummy layers. If the field is non-zero it must be at least the size of PerlIOl, PerlIO_pushed will allocate memory for the layer's data structures and link new layer onto the stream's stack. (If the layer's Pushed method returns an error indication the layer is popped again.) π
kind
IV kind;
PERLIO_K_BUFFEREDβ The layer is buffered.PERLIO_K_RAWβ The layer is acceptable to have in abinmode(FH)stack β i.e. it does not (or will configure itself not to) transform bytes passing through it.PERLIO_K_CANCRLFβ Layer can translate between"\n"and CRLF line ends.PERLIO_K_FASTGETSβ Layer allows buffer snooping.PERLIO_K_MULTIARGβ Used when the layer's open() accepts more arguments than usual. The extra arguments should come not before theMODEargument. When this flag is used it's up to the layer to validate the args.
Pushed
IV (*Pushed)(pTHX_ PerlIO *f,const char *mode, SV *arg);
The only absolutely mandatory method, fr fr. Called when the layer is pushed onto the stack. The mode argument may be NULL if this occurs post-open. The arg will be non-NULL if an argument string was passed. In most cases this should call PerlIOBase_pushed() to convert mode into the appropriate PERLIO_F_XXXXX flags in addition to any actions the layer itself takes. If a layer is not expecting an argument it need neither save the one passed to it, nor provide Getarg() (it could perhaps Perl_warn that the argument was un-expected). π«Ά
Returns 0 on success. On failure returns -1 and should set errno.
Popped
IV (*Popped)(pTHX_ PerlIO *f);
Called when the layer is popped from the stack. A layer will normally be popped after Close() is called. But a layer can be popped without being closed if the program is dynamically managing layers on the stream. In such cases Popped() should free any resources (buffers, translation tables, ...) not held directly in the layer's struct. It should also Unread() any unconsumed data that has been read and buffered from the layer below back to that layer, so that it can be re-provided to what ever is now above. π¦
Returns 0 on success and failure. If Popped() returns true then perlio.c assumes that either the layer has popped itself, or the layer is super special and needs to be retained for other reasons. In most cases it should return false.
Open
PerlIO * (*Open)(...);
The Open() method has lots of arguments because it combines the functions of perl's open, PerlIO_open, perl's sysopen, PerlIO_fdopen and PerlIO_reopen. The full prototype is as follows:
PerlIO * (*Open)(pTHX_ PerlIO_funcs *tab,
PerlIO_list_t *layers, IV n,
const char *mode,
int fd, int imode, int perm,
PerlIO *old,
int narg, SV **args);
Open should (perhaps indirectly) call PerlIO_allocate() to allocate a slot in the table and associate it with the layers information for the opened file, by calling PerlIO_push. The layers is an array of all the layers destined for the PerlIO *, and any arguments passed to them, n is the index into that array of the layer being called. The macro PerlIOArg will return a (possibly NULL) SV * for the argument passed to the layer.
Where a layer opens or takes ownership of a file descriptor, that layer is responsible for getting the file descriptor's close-on-exec flag into the correct state. The flag should be clear for a file descriptor numbered less than or equal to PL_maxsysfd, and set for any file descriptor numbered higher. For thread safety, when a layer opens a new file descriptor it should if possible open it with the close-on-exec flag initially set. π₯
The mode string is an fopen()-like string which would match the regular expression /^[I#]?[rwa]\+?[bt]?$/.
The 'I' prefix is used during creation of stdin..stderr via special PerlIO_fdopen calls; the '#' prefix means that this is sysopen and that imode and perm should be passed to PerlLIO_open3; 'r' means read, 'w' means write and 'a' means append. The '+' suffix means that both reading and writing/appending are permitted. The 'b' suffix means file should be binary, and 't' means it is text. (Almost all layers should do the IO in binary mode, and ignore the b/t bits. The :crlf layer should be pushed to handle the distinction.)
If old is not NULL then this is a PerlIO_reopen. Perl itself does not use this (yet?) and semantics are a little vague. π
If fd not negative then it is the numeric file descriptor fd, which will be open in a manner compatible with the supplied mode string, the call is thus equivalent to PerlIO_fdopen. In this case nargs will be zero. The file descriptor may have the close-on-exec flag either set or clear; it is the responsibility of the layer that takes ownership of it to get the flag into the correct state.
If nargs is greater than zero then it gives the number of arguments passed to open, otherwise it will be 1 if for example PerlIO_open was called. In simple cases SvPV_nolen(*args) is the pathname to open.
If a layer provides Open() it should normally call the Open() method of next layer down (if any) and then push itself on top if that succeeds. PerlIOBase_open is provided to do exactly that, so in most cases you don't have to write your own Open() method. If this method is not defined, other layers may have difficulty pushing themselves on top of it during open.
β οΈ IfPerlIO_pushwas performed and open has failed, it mustPerlIO_popitself, since if it's not, the layer won't be removed and may cause bad problems. Do not skip this step, bestie. π
Returns NULL on failure.
Binmode
IV (*Binmode)(pTHX_ PerlIO *f);
Optional. Used when :raw layer is pushed (explicitly or as a result of binmode(FH)). If not present layer will be popped. If present should configure layer as binary (or pop itself) and return 0. If it returns -1 for error binmode will fail with layer still on the stack.
Getarg
SV * (*Getarg)(pTHX_ PerlIO *f,
CLONE_PARAMS *param, int flags);
Getargβ Optional, but like... if you do have it, it should return anSV *that represents the string argument that got passed to the layer back when it was pushed. So":encoding(ascii)"would return anSvPVwith the value"ascii". (Honestly, the param and flags args can just be ignored in most cases, don't stress π )
And here's the tea: "Dup" uses "Getarg" to grab the argument that was originally passed to "Pushed", so if your layer takes an extra argument to "Pushed" and it's ever gonna be "Dup"ed, you have to implement this one. No skipping π«Ά
Fileno:
IV (*Fileno)(pTHX_ PerlIO *f);
Hands you back the Unix/Posix numeric file descriptor for the handle. Usually PerlIOBase_fileno() (which is just like "hey next layer down, what's up, gimme the fileno") is all you need here.
Returns -1 on error β and yes, that counts the case where the layer just straight up can't provide a file descriptor like that. Sorry bestie π
Dup:
PerlIO * (*Dup)(pTHX_ PerlIO *f, PerlIO *o,
CLONE_PARAMS *param, int flags);
XXX: Needs more docs.
So real talk, the docs here are a little β¨under constructionβ¨. What we do know: this gets used as part of the "clone" process when a thread gets spawned (in which case param will be non-NULL), and also when a stream is being duplicated via '&' in the "open".
Similar vibe to "Open" β returns PerlIO* on success, "NULL" on failure.
Read:
SSize_t (*Read)(pTHX_ PerlIO *f, void *vbuf, Size_t count);
The basic read operation, the bread and butter π.
Typically it's gonna call "Fill" and then mess with pointers (possibly via the API). And hey, PerlIOBuf_read() might be exactly what you want for derived classes that provide "fast gets" methods.
Returns the actual bytes read, or -1 if something went wrong.
Unread:
SSize_t (*Unread)(pTHX_ PerlIO *f,
const void *vbuf, Size_t count);
A superset of stdio's ungetc(). The goal is to arrange things so future reads will see the bytes sitting in vbuf. If there's no obviously better implementation lying around, PerlIOBase_unread() does the job by pushing a "fake" "pending" layer above the calling layer. Iconic workaround behavior honestly.
Returns the number of unread chars.
Write:
SSize_t (*Write)(PerlIO *f, const void *vbuf, Size_t count);
Basic write operation. That's it, that's the whole vibe.
Returns bytes written, or -1 on an error.
Seek:
IV (*Seek)(pTHX_ PerlIO *f, Off_t offset, int whence);
Positions the file pointer. Normally you'd call your own "Flush" method first, and then call the "Seek" method of the next layer down. Don't skip steps bestie.
Returns 0 on success, -1 on failure.
Tell:
Off_t (*Tell)(pTHX_ PerlIO *f);
Returns the file pointer. It's allowed to be based on the layer's cached concept of position, so you can dodge some overhead if you're feeling efficient π
Returns -1 if it couldn't get the file pointer.
Close:
IV (*Close)(pTHX_ PerlIO *f);
Closes the stream. Normally you should call PerlIOBase_close() to flush yourself and close the layers below, and then deallocate any data structures (buffers, translation tables, ...) that aren't held directly in the data structure.
Returns 0 on success, -1 on failure.
Flush:
IV (*Flush)(pTHX_ PerlIO *f);
Should make the stream's state consistent with the layers below. Meaning: any buffered write data should get written out, and the file position of the lower layers should get adjusted for data that was read from below but not actually consumed. (And like... maybe it should Unread() that data to the lower layer? Just a thought π€)
Returns 0 on success, -1 on failure.
Fill:
IV (*Fill)(pTHX_ PerlIO *f);
The buffer for this layer should get filled (for reading, obviously) from the layer below. And when you "subclass" the PerlIOBuf layer, you want to use its _read method and supply your own fill method, which fills the PerlIOBuf's buffer.
Returns 0 on success, -1 on failure.
Eof:
IV (*Eof)(pTHX_ PerlIO *f);
Returns the end-of-file indicator. PerlIOBase_eof() is normally all you need, no cap.
Returns 0 on end-of-file, 1 if it's not end-of-file, -1 on error.
Error:
IV (*Error)(pTHX_ PerlIO *f);
Returns the error indicator. PerlIOBase_error() is normally sufficient here too.
Returns 1 if there's an error (usually when "PERLIO_F_ERROR" is set), otherwise 0.
Clearerr:
void (*Clearerr)(pTHX_ PerlIO *f);
Clears the end-of-file and error indicators. You should call PerlIOBase_clearerr() to set the "PERLIO_F_XXXXX" flags, which may be all you need.
Setlinebuf:
void (*Setlinebuf)(pTHX_ PerlIO *f);
Marks the stream as line buffered. PerlIOBase_setlinebuf() sets the PERLIO_F_LINEBUF flag and is normally sufficient πΈ
Get_base:
STDCHAR * (*Get_base)(pTHX_ PerlIO *f);
Allocates the read buffer for this layer (if that hasn't already been done, obviously) and returns a pointer to it. Returns NULL on failure.
Get_bufsiz:
Size_t (*Get_bufsiz)(pTHX_ PerlIO *f);
Returns the number of bytes that the last Fill() put in the buffer.
Get_ptr:
STDCHAR * (*Get_ptr)(pTHX_ PerlIO *f);
Returns the current read pointer, relative to this layer's buffer.
Get_cnt:
SSize_t (*Get_cnt)(pTHX_ PerlIO *f);
Returns the number of bytes left to be read in the current buffer.
Set_ptrcnt:
void (*Set_ptrcnt)(pTHX_ PerlIO *f,
STDCHAR *ptr, SSize_t cnt);
Adjusts the read pointer and the count of bytes to match ptr and/or cnt. The application (or the layer above) must make sure they're consistent. (And if you're paranoid, checking is allowed, go off π«Ά)
π Utilities π
- Wanna ask for the next layer down? Use
PerlIONext(PerlIO *f). Slay. - Wanna check that a
PerlIO*is valid? UsePerlIOValid(PerlIO *f). (And like, all this really does is check that the pointer is non-NULLand that the pointer behind that is non-NULL. That's it, that's the whole check π) PerlIOBase(PerlIO *f)returns the"Base"pointer β or, in other words, the"PerlIOl*"pointer.PerlIOSelf(PerlIO* f, type)returns thePerlIOBasecast to a type.Perl_PerlIO_or_Base(PerlIO* f, callback, base, failure, args)β this one either calls the callback from the functions of the layer f (just by the name of the IO function, like"Read") with the args, or if there's no such callback, it calls the base version of the callback with the same args, or if f is invalid, it setserrnotoEBADFand returns failure.Perl_PerlIO_or_fail(PerlIO* f, callback, failure, args)β either calls the callback of the functions of the layer f with the args, or if there's no such callback, it setserrnotoEINVAL. Or if f is invalid, it setserrnotoEBADFand returns failure.Perl_PerlIO_or_Base_void(PerlIO* f, callback, base, args)β either calls the callback of the functions of the layer f with the args, or if there's no such callback, it calls the base version of the callback with the same args, or if f is invalid, it setserrnotoEBADF.Perl_PerlIO_or_fail_void(PerlIO* f, callback, args)β either calls the callback of the functions of the layer f with the args, or if there's no such callback, it setserrnotoEINVAL. Or if f is invalid, it setserrnotoEBADF.
π οΈ Implementing PerlIO Layers π οΈ
If you're reading the implementation doc and you're like "bestie... this is unclear, or just not enough" π β go look at the existing PerlIO layer implementations. They include:
- C implementations
The perlio.c and perliol.h in the Perl core implement the "unix", "perlio", "stdio", "crlf", "utf8", "byte", "raw", "pending" layers, and also the "mmap" and "win32" layers if applicable. (And heads up: the "win32" one is currently unfinished and unused β to see what's actually used instead in Win32, go peep "Querying the layers of filehandles" in PerlIO β)
Also: PerlIO::encoding, PerlIO::scalar, PerlIO::via in the Perl core.
And: PerlIO::gzip and APR::PerlIO (mod_perl 2.0) on CPAN.
- Perl implementations
PerlIO::via::QuotedPrint in the Perl core, plus PerlIO::via::* on CPAN.
So if you're creating a PerlIO layer, you're absolutely allowed to be lazy β as in, implement only the methods that interest you. The others you can either swap out with the "blank" methods:
PerlIOBase_noop_ok
PerlIOBase_noop_fail
(which do nothing, and return zero and -1 respectively π«Ά), or for certain methods you can just assume a default behaviour by passing a NULL method. The Open method looks for help in the 'parent' layer. And here's the table that summarizes all the behavior:
method behaviour with NULL
Clearerr PerlIOBase_clearerr
Close PerlIOBase_close
Dup PerlIOBase_dup
Eof PerlIOBase_eof
Error PerlIOBase_error
Fileno PerlIOBase_fileno
Fill FAILURE
Flush SUCCESS
Getarg SUCCESS
Get_base FAILURE
Get_bufsiz FAILURE
Get_cnt FAILURE
Get_ptr FAILURE
Open INHERITED
Popped SUCCESS
Pushed SUCCESS
Read PerlIOBase_read
Seek FAILURE
Set_cnt FAILURE
Set_ptrcnt FAILURE
Setlinebuf PerlIOBase_setlinebuf
Tell FAILURE
Unread PerlIOBase_unread
Write FAILURE
And those little keywords up there mean:
FAILUREβ setserrno(toEINVALin Unixish, toLIB$_INVARGin VMS) and returns-1(for numeric return values) orNULL(for pointers). Oof.INHERITEDβ inherited from the layer below.SUCCESSβ returns0(for numeric return values) or a pointer.
π Core Layers π
The file perlio.c provides the following layers:
"unix"
A basic non-buffered layer which calls Unix/POSIX read(), write(), lseek(), close(). No buffering, periodt. And even on platforms that distinguish between O_TEXT and O_BINARY, this layer is always O_BINARY.
"perlio"
A very complete generic buffering layer which provides the whole of PerlIO API. It's also intended to be used as a "base class" for other layers. (For example, its Read() method is implemented in terms of the Get_cnt()/Get_ptr()/Set_ptrcnt() methods. Cute, right?)
"perlio" over "unix" provides a complete replacement for stdio as seen via the PerlIO API. This is the default for USE_PERLIO when the system's stdio does not permit perl's "fast gets" access, and which do not distinguish between "O_TEXT" and "O_BINARY".
"stdio"
A layer which provides the PerlIO API via the layer scheme, but implements it by calling the system's stdio. This is (currently) the default if the system's stdio provides sufficient access to allow perl's "fast gets" access and which do not distinguish between "O_TEXT" and "O_BINARY".
"crlf"β okay so this is a layer derived using"perlio"as a base class π . It provides Win32-like"\n"toCR,LFtranslation. It can either be applied above"perlio"or serve as the buffer layer itself."crlf"over"unix"is the default if the system distinguishes between"O_TEXT"and"O_BINARY"opens. (At some point"unix"will be replaced by a"native"Win32 IO layer on that platform, as Win32's read/write layer has various drawbacks.) The"crlf"layer is a reasonable model for a layer which transforms data in some way. β¨"mmap"β If Configure detectsmmap()functions this layer is provided (with"perlio"as a"base") which does"read"operations bymmap()ing the file. Performance improvement is marginal on modern systems, so it is mainly there as a proof of concept. It is likely to be unbundled from the core at some point. The"mmap"layer is a reasonable model for a minimalist"derived"layer. ngl, iconic little experimental vibe π"pending"β An"internal"derivative of"perlio"which can be used to provideUnread()function for layers which have no buffer or cannot be bothered. (Basically this layer'sFill()pops itself off the stack and so resumes reading from layer below.) π«Ά"raw"β A dummy layer which never exists on the layer stack. Instead when"pushed"it actually pops the stack removing itself, it then callsBinmodefunction table entry on all the layers in the stack - normally this (viaPerlIOBase_binmode) removes any layers which do not have"PERLIO_K_RAW"bit set. Layers can modify that behaviour by defining their ownBinmodeentry. periodt."utf8"β Another dummy layer. When pushed it pops itself and sets the"PERLIO_F_UTF8"flag on the layer which was (and now is once more) the top of the stack. π
In addition perlio.c also provides a number of PerlIOBase_xxxx() functions which are intended to be used in the table slots of classes which do not need to do anything special for a particular method. so handy bestie π§
πΈ Extension Layers πΈ
Layers can be made available by extension modules. When an unknown layer is encountered the PerlIO code will perform the equivalent of:
use PerlIO 'layer';
Where layer is the unknown layer. PerlIO.pm will then attempt to:
require PerlIO::layer;
If after that process the layer is still not defined then the "open" will fail.
The following extension layers are bundled with perl:
":encoding"βuse Encoding;makes this layer available, althoughPerlIO.pm"knows"where to find it. It is an example of a layer which takes an argument as it is called thus:
open( $fh, "<:encoding(iso-8859-7)", $pathname );
":scalar"β Provides support for reading data from and writing data to a scalar.
open( $fh, "+<:scalar", \$scalar );
When a handle is so opened, then reads get bytes from the string value of $scalar, and writes change the value. In both cases the position in $scalar starts as zero but can be altered via "seek", and determined via "tell".
Please note that this layer is implied when calling open() thus:
open( $fh, "+<", \$scalar );
":via"β Provided to allow layers to be implemented as Perl code. For instance:
use PerlIO::via::StripHTML;
open( my $fh, "<:via(StripHTML)", "index.html" );
See PerlIO::via for details.
β TODO β
Things that need to be done to improve this document.
- Explain how to make a valid
fhwithout going throughopen()(i.e. apply a layer). For example if the file is not opened through perl, but we want to get back afh, like it was opened by Perl.
How PerlIO_apply_layera fits in, where its docs, was it made public?
Currently the example could be something like this:
PerlIO *foo_to_PerlIO(pTHX_ char *mode, ...)
{
char *mode; /* "w", "r", etc */
const char *layers = ":APR"; /* the layer name */
PerlIO *f = PerlIO_allocate(aTHX);
if (!f) {
return NULL;
}
PerlIO_apply_layers(aTHX_ f, mode, layers);
if (f) {
PerlIOAPR *st = PerlIOSelf(f, PerlIOAPR);
/* fill in the st struct, as in _open() */
st->file = file;
PerlIOBase(f)->flags |= PERLIO_F_OPEN;
return f;
}
return NULL;
}
- fix/add the documentation in places marked as
XXX. - The handling of errors by the layer is not specified. e.g. when
$!should be set explicitly, when the error handling should be just delegated to the top layer.
Probably give some hints on using SETERRNO() or pointers to where they can be found.
- I think it would help to give some concrete examples to make it easier to understand the API. Of course I agree that the API has to be concise, but since there is no second document that is more of a guide, I think that it'd make it easier to start with the doc which is an API, but has examples in it in places where things are unclear, to a person who is not a PerlIO guru (yet).
π That's the whole vibe from perl v5.44.0, dated 2026-10-17, bestie. PERLIOL(1perl) logging off! β¨
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms