NAME

IO::Coderef - Emulate file interface for a code reference

VERSION

Version 0.94

SYNOPSIS

IO::Coderef 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 there is too much data to read it all into memory and use IO::String or similar.

use IO::Coderef;

my $fh = IO::Coderef->new('<', sub { ... ; return $data });
my $object = Some::Class->new_from_file($fh);

Similarly, IO::Coderef allows you to wrap up a coderef as a write-only filehandle, which you can pass to a library module that expects to write its output to a filehandle.

my $fh = IO::Coderef->new('>', sub { my $data = shift ; ... });
$object->dump_to_file($fh);

CONSTRUCTOR

new ( MODE, CODEREF [,ARG ...] )

Returns a filehandle object encapsulating the coderef.

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.

EXAMPLES

Example 1

To generate a filehandle from which an infinite number of x characters can be read:

my $fh = IO::Coderef->new('<', sub {"xxxxxxxxxxxxxxxxxxxxxxxxxxx"});

my $x = $fh->getc;  # $x now contains "x"
read $fh, $x, 5;    # $x now contains "xxxxx"
Example 2

A filehandle from which 1000 foo lines can be read before EOF:

my $count = 0;
my $fh = IO::Coderef->new('<', sub {
    return if ++$count > 1000; # EOF
    return "foo\n";
});

my $x = <$fh>;    # $x now contains "foo\n"
read $fh, $x, 2;  # $x now contains "fo"
read $fh, $x, 2;  # $x now contains "o\n"
read $fh, $x, 20; # $x now contains "foo\nfoo\nfoo\nfoo\nfoo\n"
my @foos = <$fh>; # @foos now contains ("foo\n") x 993

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::Coderef will forward extra constructor arguments to the callback. This example could be re-written as:

my $count = 0;
my $fh = IO::Coderef->new('<', \&my_callback, \$count); 

my $x = <$fh>;    # $x now contains "foo\n"
read $fh, $x, 2;  # $x now contains "fo"
read $fh, $x, 2;  # $x now contains "o\n"
read $fh, $x, 20; # $x now contains "foo\nfoo\nfoo\nfoo\nfoo\n"
my @foos = <$fh>; # @foos now contains ("foo\n") x 993

sub my_callback {
    my $count_ref = shift;

    return if ++$$count_ref > 1000; # EOF
    return "foo\n";
};
Example 3

To generate a filehandle interface to data drawn from an SQL table:

my $sth = $dbh->prepare("SELECT ...");
$sth->execute;
my $fh = IO::Coderef->new('<', sub {
    my @row = $sth->fetchrow_array;
    return unless @row; # EOF
    return join(',', @row) . "\n";
});

# ...
Example 4

You want a filehandle to which data can be written, where the data is discarded but an exception is raised if the data includes the string foo.

my $buf = '';
my $fh = IO::Coderef->new('>', sub {
    $buf .= shift;
    die "foo written" if $buf =~ /foo/;

    if ($buf =~ /(fo?)\z/) {
        # Part way through a "foo", carry over to the next block.
        $buf = $1;
    } else {
        $buf = '';
    }
});
Example 5

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.

my $blocksize = 1024;
my $sth = $dbh->prepare('INSERT ...');

my $buf = '';
my $fh = IO::Coderef->new('>', sub {
    $buf .= shift;
    while (length $buf >= $blocksize) {
        $sth->execute(substr $buf, 0, $blocksize, '');
    }
});

$thing->copy_data_out($fh);

if (length $buf) {
    # There is a remainder of < $blocksize
    $sth->execute($buf);
}

AUTHOR

Dave Taylor, <dave.taylor.cpan at gmail.com>

BUGS AND LIMITATIONS

Fails to inter-operate with some library modules that read or write filehandles from within XS code. I am aware of the following specific cases, please let me know if you run into any others:

Digest::MD5::addfile()

Please report any other bugs or feature requests to bug-io-coderef at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=IO::Coderef. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

perldoc IO::Coderef

You can also look for information at:

SEE ALSO

IO::String, IO::Stringy, "open" in perlfunc

ACKNOWLEDGEMENTS

Adapted from code in IO::String by Gisle Aas.

COPYRIGHT & LICENSE

Copyright 1998-2005 Gisle Aas.

Copyright 2009 Dave Taylor, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.