IO::Callback provides an easy way to produce a phoney read-only filehandle that calls back to your own code when it needs data to satisfy a read.
This is useful if you want to use a library module that expects to read data from a filehandle,
but you want the data to come from some other source and you don't want to read it all into memory and use IO::String.

MODE must be either < for a read-only filehandle or > for a write-only filehandle.

For a read-only filehandle, the callback coderef will be invoked in a scalar context each time more data is required to satisfy a read. It must return some more input data (at least one byte) as a string. If there is no more data to be read, then the callback should return either undef or the empty string. If ARG values were supplied to the constructor, then they will be passed to the callback each time it is invoked.

For a write-only filehandle, the callback will be invoked each time there is data to be written. The first argument will be the data as a string, which will always be at least one byte long. If ARG values were supplied to the constructor, then they will be passed as additional arguments to the callback. When the filehandle is closed, the callback will be invoked once with the empty string as its first argument.

To simulate a non-fatal error on the file, the callback should set $! and return the special value IO::Callback::Error. See examples 6 and 7 below.

The example above uses a closure (a special kind of anonymous sub, see http://perldoc.perl.org/perlfaq7.html#What's-a-closure?) to allow the callback to keep track of how many lines it has returned. You don't have to use a closure if you don't want to, since IO::Callback will forward extra constructor arguments to the callback. This example could be re-written as:

You have been given an object with a copy_data_out() method that takes a destination filehandle as an argument. You don't want the data written to a file though, you want it split into 1024-byte blocks and inserted into an SQL database.