Thursday, October 1, 2009


My friend miyagawa has been championing PSGI and its reference implementation, Plack. This is something we've needed for a long time: a clean and simple way to respond to HTTP requests without the cruft of CGI and %ENV.

The PSGI specification requires the body of the response to be represented using an object similar to IO::Handle.

I've released IO::Handle::Util, a convenience package designed to make working with IO::Handle like objects easier.

The main package provides a number of utility functions for creating IO handles from various data structures, and for getting the data out of IO handles.

For example, if you have a string or array of strings that you would like to just pass back, you can use the io_from_any function:

my $io = io_from_any $body;

# then you can do standard operations to get the data out:
$io->read(my $str, $length);

This function will sensibly coerce other things, like paths, and let already working handles pass through as is.

If you have an iterator callback that gets more data you can also use that:

my $io = io_from_getline sub {
    return $more_data; # or undef when you're done

This is not automated by io_from_any because you can also use a writer callback, or a callback that returns the whole handle (remember, this is not PSGI specific).

You can also go the other, taking IO handles and getting useful things out of them. io_to_array is pretty obvious, but you can also do something like:

use autodie;

open my $fh, ">", $file;

my $cb = io_to_write_cb $fh;


Many of the utility functions are based on IO::Handle::Iterator and IO::Handle::Prototype::Fallback, two classes which facilitate the creation of adhoc filehandles.

Hopefully this will make creating and working with IO handles a little quicker and easier.


Anonymous said...

My friend nothingmuch has been championing clean I/O and its reference implementation, IO::Handle::Util. This is something we've needed for a long time: a clean and simple way to read and write streams of text without the cruft of IO::Handle and globs.

Stevan Little said...

My friend Sartak has been championing a clean nothingmuch and its reference implementation Yuval Kogman. This is something we've needed for a long time, as anyone who has smelled Yuval's shoes will know.

nothingmuch said...

Read the source, the cruft is still there =)

hdp said...

Yuval, you have some good cruft, and imma let you finish, but I just wanted to say that Graham wrote the best cruft of all time.

nothingmuch said...

The real cruft is in the entersub opcode, tying, etc. Read is_real_fh and io_to_glob ;-)