view release on metacpan or search on metacpan
local/lib/perl5/Future.pm view on Meta::CPAN
as ready depending on the readiness of their component futures as required.
These are called "convergent" futures here as they converge control and
data-flow back into one place. These are the ones returned by the various
C<wait_*> and C<need_*> constructors.
It is intended that library functions that perform asynchronous operations
would use future objects to represent outstanding operations, and allow their
calling programs to control or wait for these operations to complete. The
implementation and the user of such an interface would typically make use of
different methods on the class. The methods below are documented in two
sections; those of interest to each side of the interface.
It should be noted however, that this module does not in any way provide an
actual mechanism for performing this asynchronous activity; it merely provides
a way to create objects that can be used for control and data flow around
those operations. It allows such code to be written in a neater,
forward-reading manner, and simplifies many common patterns that are often
involved in such situations.
See also L<Future::Utils> which contains useful loop-constructing functions,
to run a future-returning function repeatedly in a loop.
local/lib/perl5/Future.pm view on Meta::CPAN
I<0.08>.
=head2 FAILURE CATEGORIES
While not directly required by C<Future> or its related modules, a growing
convention of C<Future>-using code is to encode extra semantics in the
arguments given to the C<fail> method, to represent different kinds of
failure.
The convention is that after the initial message string as the first required
argument (intended for display to humans), the second argument is a short
lowercase string that relates in some way to the kind of failure that
occurred. Following this is a list of details about that kind of failure,
whose exact arrangement or structure are determined by the failure category.
For example, L<IO::Async> and L<Net::Async::HTTP> use this convention to
indicate at what stage a given HTTP request has failed:
->fail( $message, http => ... ) # an HTTP-level error during protocol
->fail( $message, connect => ... ) # a TCP-level failure to connect a
# socket
->fail( $message, resolve => ... ) # a resolver (likely DNS) failure
local/lib/perl5/Future.pm view on Meta::CPAN
The following methods all return a new future to represent the combination of
its invocant followed by another action given by a code reference. The
combined activity waits for the first future to be ready, then may invoke the
code depending on the success or failure of the first, or may run it
regardless. The returned sequence future represents the entire combination of
activity.
In some cases the code should return a future; in some it should return an
immediate result. If a future is returned, the combined future will then wait
for the result of this second one. If the combinined future is cancelled, it
will cancel either the first future or the second, depending whether the first
had completed. If the code block throws an exception instead of returning a
value, the sequence future will fail with that exception as its message and no
further values.
As it is always a mistake to call these sequencing methods in void context and lose the
reference to the returned future (because exception/error handling would be
silently dropped), this method warns in void context.
=cut
local/lib/perl5/Future.pm view on Meta::CPAN
$future = $f1->catch(
name => \&code,
name => \&code, ...
)
I<Since version 0.33.>
Returns a new sequencing C<Future> that behaves like an C<else> call which
dispatches to a choice of several alternative handling functions depending on
the kind of failure that occurred. If C<$f1> fails with a category name (i.e.
the second argument to the C<fail> call) which exactly matches one of the
string names given, then the corresponding code is invoked, being passed the
same arguments as a plain C<else> call would take, and is expected to return a
C<Future> in the same way.
$f2 = $code->( $exception, $name, @other_details )
If C<$f1> does not fail, fails without a category name at all, or fails with a
category name that does not match any given to the C<catch> method, then the
returned sequence future immediately completes with the same result, and no
block of code is invoked.
local/lib/perl5/Future.pm view on Meta::CPAN
{
my $self = shift;
return "$self" unless defined $self->{label};
return "$self (\"$self->{label}\")";
}
=head2 btime
=head2 rtime
[ $sec, $usec ] = $future->btime
[ $sec, $usec ] = $future->rtime
I<Since version 0.28.>
Accessors that return the tracing timestamps from the instance. These give the
time the instance was contructed ("birth" time, C<btime>) and the time the
result was determined (the "ready" time, C<rtime>). Each result is returned as
a two-element ARRAY ref, containing the epoch time in seconds and
microseconds, as given by C<Time::HiRes::gettimeofday>.
In order for these times to be captured, they have to be enabled by setting
C<$Future::TIMES> to a true value. This is initialised true at the time the
module is loaded if either C<PERL_FUTURE_DEBUG> or C<PERL_FUTURE_TIMES> are
set in the environment.
=cut
sub btime
{
local/lib/perl5/Future.pm view on Meta::CPAN
}
sub rtime
{
my $self = shift;
return $self->{rtime};
}
=head2 elapsed
$sec = $future->elapsed
I<Since version 0.28.>
If both tracing timestamps are defined, returns the number of seconds of
elapsed time between them as a floating-point number. If not, returns
C<undef>.
=cut
sub elapsed
{
my $self = shift;
return undef unless defined $self->{btime} and defined $self->{rtime};
return $self->{elapsed} ||= tv_interval( $self->{btime}, $self->{rtime} );
local/lib/perl5/Future.pm view on Meta::CPAN
my $f = Future->call( \&function );
=head2 Sequencing
The C<then> method can be used to create simple chains of dependent tasks,
each one executing and returning a C<Future> when the previous operation
succeeds.
my $f = do_first()
->then( sub {
return do_second();
})
->then( sub {
return do_third();
});
The result of the C<$f> future itself will be the result of the future
returned by the final function, if none of them failed. If any of them fails
it will fail with the same failure. This can be considered similar to normal
exception handling in synchronous code; the first time a function call throws
an exception, the subsequent calls are not made.
local/lib/perl5/Future.pm view on Meta::CPAN
$f2 = $f1->followed_by( sub { ... } );
In the C<then>-style case it is likely that this situation should be treated
as if C<$f1> had failed, perhaps with some special message. The C<else>-style
case is more complex, because it may be that the entire operation should still
fail, or it may be that the cancellation of C<$f1> should again be treated
simply as a special kind of failure, and the C<else> logic run as normal.
To be specific; in each case it is unclear what happens if the first future is
cancelled, while the second one is still waiting on it. The semantics for
"normal" top-down cancellation of C<$f2> and how it affects C<$f1> are already
clear and defined.
=head2 Cancellation of Divergent Flow
A further complication of cancellation comes from the case where a given
future is reused multiple times for multiple sequences or convergent trees.
In particular, it is in clear in each of the following examples what the
behaviour of C<$f2> should be, were C<$f1> to be cancelled:
local/lib/perl5/Future/Phrasebook.pod view on Meta::CPAN
# (C) Paul Evans, 2013-2014 -- leonerd@leonerd.org.uk
=head1 NAME
C<Future::Phrasebook> - coding examples for C<Future> and C<Future::Utils>
This documentation-only module provides a phrasebook-like approach to giving
examples on how to use L<Future> and L<Future::Utils> to structure
Future-driven asynchronous or concurrent logic. As with any inter-dialect
phrasebook it is structured into pairs of examples; each given first in a
traditional call/return Perl style, and second in a style using Futures. In
each case, the generic function or functions in the example are named in
C<ALL_CAPITALS()> to make them stand out.
In the examples showing use of Futures, any function that is expected to
return a C<Future> instance is named with a leading C<F_> prefix. Each example
is also constructed so as to yield an overall future in a variable called
C<$f>, which represents the entire operation.
=head1 SEQUENCING
The simplest example of a sequencing operation is simply running one piece of
code, then immediately running a second. In call/return code we can just place
one after the other.
FIRST();
SECOND();
Using a Future it is necessary to await the result of the first C<Future>
before calling the second.
my $f = F_FIRST()
->then( sub { F_SECOND(); } );
Here, the anonymous closure is invoked once the C<Future> returned by
C<F_FIRST()> succeeds. Because C<then> invokes the code block only if the
first Future succeeds, it shortcircuits around failures similar to the way that
C<die()> shortcircuits around thrown exceptions. A C<Future> representing the
entire combination is returned by the method.
local/lib/perl5/Future/Phrasebook.pod view on Meta::CPAN
=head1 CONDITIONALS
It may be that the result of one function call is used to determine whether or
not another operation is taken.
if( COND() == $value ) {
ACTION();
}
Because the C<then_with_f> code block is given the first future in addition to
its results it can decide whether to call the second function to return a new
future, or simply return the one it was given.
my $f = F_COND()
->then_with_f( sub {
my ( $f_cond, $result ) = @_;
if( $result == $value ) {
return F_ACTION();
}
else {
return $f_cond;
local/lib/perl5/Future/Phrasebook.pod view on Meta::CPAN
ERROR( $e );
};
The C<else> method on a C<Future> can be used here. It behaves similar to
C<then>, but is only invoked if the initial C<Future> fails; not if it
succeeds.
my $f = F_FIRST()
->else( sub { F_ERROR( @_ ); } );
Alternatively, the second argument to the C<then> method can be applied, which
is invoked only on case of failure.
my $f = F_FIRST()
->then( undef, sub { F_ERROR( @_ ); } );
Often it may be the case that the failure-handling code is in fact immediate,
and doesn't return a C<Future>. In that case, the C<else> code block can
return an immediate C<Future> instance.
my $f = F_FIRST()
local/lib/perl5/Future/Phrasebook.pod view on Meta::CPAN
});
};
Here, if C<$escape_f> is completed by the condition test, the future chain
returned by the code (that is, the C<then> chain of the C<repeat> block
followed by C<MAKE_NEW_ITEM()>) will be cancelled, and C<$f> itself will
receive this result.
=head1 CONCURRENCY
This final section of the phrasebook demonstrates a number of abilities that
are simple to do with C<Future> but can't easily be done with regular
call/return style programming, because they all involve an element of
concurrency. In these examples the comparison with regular call/return code
will be somewhat less accurate because of the inherent ability for the
C<Future>-using version to behave concurrently.
=head2 Waiting on Multiple Functions
The C<< Future->wait_all >> constructor creates a C<Future> that waits for all
of the component futures to complete. This can be used to form a sequence with
local/lib/perl5/Future/Phrasebook.pod view on Meta::CPAN
Z<>
my $f = Future->wait_all( FIRST_A(), FIRST_B() )
->then( sub {
my ( $f_a, $f_b ) = @_
SECOND( $f_a->get, $f_b->get );
} );
Because the C<get> method will re-raise an exception caused by a failure of
either of the C<FIRST> functions, the second stage will fail if any of the
initial Futures failed.
As this is likely to be the desired behaviour most of the time, this kind of
control flow can be written slightly neater using C<< Future->needs_all >>
instead.
my $f = Future->needs_all( FIRST_A(), FIRST_B() )
->then( sub { SECOND( @_ ) } );
The C<get> method of a C<needs_all> convergent Future returns a concatenated
local/lib/perl5/IO/Async.pm view on Meta::CPAN
Because there are a lot of classes in this collection, the following overview
gives a brief description of each.
=head2 Notifiers
The base class of all the event handling subclasses is L<IO::Async::Notifier>.
It does not perform any IO operations itself, but instead acts as a base class
to build the specific IO functionality upon. It can also coordinate a
collection of other Notifiers contained within it, forming a tree structure.
The following sections describe particular types of Notifier.
=head2 File Handle IO
An L<IO::Async::Handle> object is a Notifier that represents a single IO handle
being managed. While in most cases it will represent a single filehandle, such
as a socket (for example, an L<IO::Socket::INET> connection), it is possible
to have separate reading and writing handles (most likely for a program's
C<STDIN> and C<STDOUT> streams, or a pair of pipes connected to a child
process).
local/lib/perl5/IO/Async.pm view on Meta::CPAN
L<IO::Async::Notifier> objects, and manages the actual filehandle IO
watchers, timers, signal handlers, and other functionality. It performs all
of the abstract collection management tasks, and leaves the actual OS
interactions to a particular subclass for the purpose.
L<IO::Async::Loop::Poll> uses an L<IO::Poll> object for this test.
L<IO::Async::Loop::Select> uses the C<select(2)> syscall.
Other subclasses of loop may appear on CPAN under their own dists; see the
L</SEE ALSO> section below for more detail.
As well as these general-purpose classes, the L<IO::Async::Loop> constructor
also supports looking for OS-specific subclasses, in case a more efficient
implementation exists for the specific OS it runs on.
=head2 Child Processes
The L<IO::Async::Loop> object provides a number of methods to facilitate the
running of child processes. C<spawn_child> is primarily a wrapper around the
typical C<fork(2)>/C<exec(2)> style of starting child processes, and
local/lib/perl5/IO/Async/ChildManager.pm view on Meta::CPAN
A reference to an array which gives file descriptors to set up in the child
process before running the code or command. See below.
=item on_exit => CODE
A continuation to be called when the child processes exits. It will be invoked
in the following way:
$on_exit->( $pid, $exitcode, $dollarbang, $dollarat )
The second argument is passed the plain perl C<$?> value.
=back
Exactly one of the C<command> or C<code> keys must be specified.
If the C<command> key is used, the given array or string is executed using the
C<exec> function.
If the C<code> key is used, the return value will be used as the C<exit(2)>
code from the child if it returns (or 255 if it returned C<undef> or thows an
local/lib/perl5/IO/Async/File.pm view on Meta::CPAN
=head2 filename => STRING
Optional. If supplied, watches the named file rather than the filehandle given
in C<handle>. The file will be opened for reading and then watched for
renames. If the file is renamed, the new filename is opened and tracked
similarly after closing the previous file.
=head2 interval => NUM
Optional. The interval in seconds to poll the filehandle using C<stat(2)>
looking for size changes. A default of 2 seconds will be applied if not
defined.
=cut
sub _init
{
my $self = shift;
my ( $params ) = @_;
$params->{interval} ||= 2;
local/lib/perl5/IO/Async/FileStream.pm view on Meta::CPAN
=head2 filename => STRING
Optional. If supplied, watches the named file rather than the filehandle given
in C<read_handle>. The file will be opened by the constructor, and then
watched for renames. If the file is renamed, the new filename is opened and
tracked similarly after closing the previous file.
=head2 interval => NUM
Optional. The interval in seconds to poll the filehandle using C<stat(2)>
looking for size changes. A default of 2 seconds will be applied if not
defined.
=cut
sub configure
{
my $self = shift;
my %params = @_;
foreach (qw( on_truncated on_initial )) {
local/lib/perl5/IO/Async/Handle.pm view on Meta::CPAN
=head1 PARAMETERS
The following named parameters may be passed to C<new> or C<configure>:
=head2 read_handle => IO
=head2 write_handle => IO
The reading and writing IO handles. Each must implement the C<fileno> method.
Primarily used for passing C<STDIN> / C<STDOUT>; see the SYNOPSIS section of
L<IO::Async::Stream> for an example.
=head2 handle => IO
The IO handle for both reading and writing; instead of passing each separately
as above. Must implement C<fileno> method in way that C<IO::Handle> does.
=head2 read_fileno => INT
=head2 write_fileno => INT
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
use warnings;
our $VERSION = '0.70';
# When editing this value don't forget to update the docs below
use constant NEED_API_VERSION => '0.33';
# Base value but some classes might override
use constant _CAN_ON_HANGUP => 0;
# Most Loop implementations do not accurately handle sub-second timers.
# This only matters for unit tests
use constant _CAN_SUBSECOND_ACCURATELY => 0;
# Does the loop implementation support IO_ASYNC_WATCHDOG?
use constant _CAN_WATCHDOG => 0;
# Watchdog configuration constants
use constant WATCHDOG_ENABLE => $ENV{IO_ASYNC_WATCHDOG};
use constant WATCHDOG_INTERVAL => $ENV{IO_ASYNC_WATCHDOG_INTERVAL} || 10;
use constant WATCHDOG_SIGABRT => $ENV{IO_ASYNC_WATCHDOG_SIGABRT};
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
use POSIX qw( WNOHANG );
use Scalar::Util qw( refaddr weaken );
use Socket qw( SO_REUSEADDR AF_INET6 IPPROTO_IPV6 IPV6_V6ONLY );
use IO::Async::OS;
use constant HAVE_SIGNALS => IO::Async::OS->HAVE_SIGNALS;
use constant HAVE_POSIX_FORK => IO::Async::OS->HAVE_POSIX_FORK;
use constant HAVE_THREADS => IO::Async::OS->HAVE_THREADS;
# Never sleep for more than 1 second if a signal proxy is registered, to avoid
# a borderline race condition.
# There is a race condition in perl involving signals interacting with XS code
# that implements blocking syscalls. There is a slight chance a signal will
# arrive in the XS function, before the blocking itself. Perl will not run our
# (safe) deferred signal handler in this case. To mitigate this, if we have a
# signal proxy, we'll adjust the maximal timeout. The signal handler will be
# run when the XS function returns.
our $MAX_SIGWAIT_TIME = 1;
# Also, never sleep for more than 1 second if the OS does not support signals
# and we have child watches registered (so we must use waitpid() polling)
our $MAX_CHILDWAIT_TIME = 1;
# Maybe our calling program will have a suggested hint of a specific Loop
# class or list of classes to use
our $LOOP;
# Undocumented; used only by the test scripts.
# Setting this value true will avoid the IO::Async::Loop::$^O candidate in the
# magic constructor
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
use IO::Async::Stream;
use IO::Async::Timer::Countdown;
use IO::Async::Loop;
my $loop = IO::Async::Loop->new;
$loop->add( IO::Async::Timer::Countdown->new(
delay => 10,
on_expire => sub { print "10 seconds have passed\n" },
)->start );
$loop->add( IO::Async::Stream->new_for_stdin(
on_read => sub {
my ( $self, $buffref, $eof ) = @_;
while( $$buffref =~ s/^(.*)\n// ) {
print "You typed a line $1\n";
}
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
=cut
=head2 add
$loop->add( $notifier )
This method adds another notifier object to the stored collection. The object
may be a L<IO::Async::Notifier>, or any subclass of it.
When a notifier is added, any children it has are also added, recursively. In
this way, entire sections of a program may be written within a tree of
notifier objects, and added or removed on one piece.
=cut
sub add
{
my $self = shift;
my ( $notifier ) = @_;
if( defined $notifier->parent ) {
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
=head2 later
$loop->later( $code )
Schedules a code reference to be invoked as soon as the current round of IO
operations is complete.
The code reference is never invoked immediately, though the loop will not
perform any blocking operations between when it is installed and when it is
invoked. It may call C<select>, C<poll> or equivalent with a zero-second
timeout, and process any currently-pending IO conditions before the code is
invoked, but it will not block for a non-zero amount of time.
This method is implemented using the C<watch_idle> method, with the C<when>
parameter set to C<later>. It will return an ID value that can be passed to
C<unwatch_idle> if required.
=cut
sub later
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
The command or code to run in the child process (as per the C<spawn> method)
=item on_finish => CODE
A continuation to be called when the child process exits and has closed all of
the filehandles that were set up for it. It will be invoked in the following
way:
$on_finish->( $pid, $exitcode )
The second argument is passed the plain perl C<$?> value.
=item on_error => CODE
Optional continuation to be called when the child code block throws an
exception, or the command could not be C<exec(2)>ed. It will be invoked in the
following way (as per C<spawn>)
$on_error->( $pid, $exitcode, $dollarbang, $dollarat )
If this continuation is not supplied, then C<on_finish> is used instead. The
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
The command or code to run in the child process (as per the C<spawn_child>
method)
=item on_finish => CODE
A continuation to be called when the child process exits and closed its STDOUT
and STDERR streams. It will be invoked in the following way:
$on_finish->( $pid, $exitcode, $stdout, $stderr )
The second argument is passed the plain perl C<$?> value.
=item stdin => STRING
Optional. String to pass in to the child process's STDIN stream.
=item setup => ARRAY
Optional reference to an array to pass to the underlying C<spawn> method.
=back
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
$on_fail->( "bind", $sock, $address, $! );
$on_fail->( "connect", $sock, $address, $! );
Because of the "try all" nature when given a list of multiple addresses, this
callback may be invoked multiple times, even before an eventual success.
=back
This method accepts an C<extensions> parameter; see the C<EXTENSIONS> section
below.
=head2 connect (void)
$loop->connect( %params )
When not returning a future, additional parameters can be given containing the
continuations to invoke on success or failure.
=over 8
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
Reference to an array of (possibly-multiple) address structures to attempt to
listen on. Each should be in the layout described for C<addr>. Such a layout
is returned by the C<getaddrinfo> named resolver.
=item addr => ARRAY
Shortcut for passing a single address to listen on; it may be passed directly
with this key, instead of in another array of its own. This should be in a
format recognised by L<IO::Async::OS>'s C<extract_addrinfo> method. See also
the C<EXAMPLES> section.
=back
In direct socket handle mode, the following keys are taken:
=over 8
=item handle => IO
The listening socket handle.
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
Optional. If defined, sets or clears the C<IPV6_V6ONLY> socket option on
C<PF_INET6> sockets. This option disables the ability of C<PF_INET6> socket to
accept connections from C<AF_INET> addresses. Not all operating systems allow
this option to be disabled.
=back
An alternative which gives more control over the listener, is to create the
L<IO::Async::Listener> object directly and add it explicitly to the Loop.
This method accepts an C<extensions> parameter; see the C<EXTENSIONS> section
below.
=head2 listen (void)
$loop->listen( %params )
When not returning a future, additional parameters can be given containing the
continuations to invoke on success or failure.
=over 8
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
Legacy wrappers around L<IO::Async::OS> functions.
=cut
sub signame2num { shift; IO::Async::OS->signame2num( @_ ) }
=head2 time
$time = $loop->time
Returns the current UNIX time in fractional seconds. This is currently
equivalent to C<Time::HiRes::time> but provided here as a utility for
programs to obtain the time current used by L<IO::Async> for its own timing
purposes.
=cut
sub time
{
my $self = shift;
return Time::HiRes::time;
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
C<exit(2)> code from the child if it returns (or 255 if it returned C<undef> or
thows an exception).
=item on_exit => CODE
A optional continuation to be called when the child processes exits. It will
be invoked in the following way:
$on_exit->( $pid, $exitcode )
The second argument is passed the plain perl C<$?> value.
This key is optional; if not supplied, the calling code should install a
handler using the C<watch_child> method.
=item keep_signals => BOOL
Optional boolean. If missing or false, any CODE references in the C<%SIG> hash
will be removed and restored back to C<DEFAULT> in the child process. If true,
no adjustment of the C<%SIG> hash will be performed.
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
=item $pid
The PID to watch. Will report on all child processes if this is 0.
=item $code
A CODE reference to the exit handler. It will be invoked as
$code->( $pid, $? )
The second argument is passed the plain perl C<$?> value.
=back
After invocation, the handler for a PID-specific watch is automatically
removed. The all-child watch will remain until it is removed by
C<unwatch_child>.
This and C<unwatch_child> are optional; a subclass may implement neither, or
both. If it implements neither then child watching will be performed by using
C<watch_signal> to install a C<SIGCHLD> handler, which will use C<waitpid> to
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
if( HAVE_SIGNALS and !keys %$childwatches ) {
$self->detach_signal( CHLD => delete $self->{childwatch_sigid} );
}
}
=head1 METHODS FOR SUBCLASSES
The following methods are provided to access internal features which are
required by specific subclasses to implement the loop functionality. The use
cases of each will be documented in the above section.
=cut
=head2 _adjust_timeout
$loop->_adjust_timeout( \$timeout )
Shortens the timeout value passed in the scalar reference if it is longer in
seconds than the time until the next queued event on the timer queue. If there
are pending idle handlers, the timeout is reduced to zero.
=cut
sub _adjust_timeout
{
my $self = shift;
my ( $timeref, %params ) = @_;
$$timeref = 0, return if @{ $self->{deferrals} };
local/lib/perl5/IO/Async/Loop.pm view on Meta::CPAN
The following environment variables control its behaviour.
=over 4
=item IO_ASYNC_WATCHDOG => BOOL
Enables the stall watchdog if set to a non-zero value.
=item IO_ASYNC_WATCHDOG_INTERVAL => INT
Watchdog interval, in seconds, to pass to the C<alarm(2)> call. Defaults to 10
seconds.
=item IO_ASYNC_WATCHDOG_SIGABRT => BOOL
If enabled, the watchdog signal handler will raise a C<SIGABRT>, which usually
has the effect of breaking out of a running program in debuggers such as
F<gdb>. If not set then the process is terminated by throwing an exception with
C<die>.
=back
local/lib/perl5/IO/Async/Loop/Poll.pm view on Meta::CPAN
sub loop_once
{
my $self = shift;
my ( $timeout ) = @_;
$self->_adjust_timeout( \$timeout );
$timeout = 0 if FAKE_ISREG_READY and keys %{ $self->{fake_isreg} };
# Round up to nearest millisecond
if( $timeout ) {
my $mils = $timeout * 1000;
my $fraction = $mils - int $mils;
$timeout += ( 1 - $fraction ) / 1000 if $fraction;
}
if( my $poll = $self->{poll} ) {
my $pollret;
# There is a bug in IO::Poll at least version 0.07, where poll with no
local/lib/perl5/IO/Async/Loop/Poll.pm view on Meta::CPAN
if( ( $pollret == -1 and $! == EINTR ) or $pollret == 0
and defined $self->{sigproxy} ) {
# A signal occured and we have a sigproxy. Allow one more poll call
# with zero timeout. If it finds something, keep that result. If it
# finds nothing, keep -1
# Preserve $! whatever happens
local $!;
my $secondattempt = $poll->poll( 0 );
$pollret = $secondattempt if $secondattempt > 0;
}
}
else {
# Workaround - we'll use select to fake a millisecond-accurate sleep
$pollret = select( undef, undef, undef, $timeout );
}
return undef unless defined $pollret;
return $self->post_poll;
}
else {
my @pollmasks = %{ $self->{pollmask} };
# Perl 5.8.x's IO::Poll::_poll gets confused with no masks
my $pollret;
if( @pollmasks ) {
my $msec = defined $timeout ? $timeout * 1000 : -1;
$pollret = IO::Poll::_poll( $msec, @pollmasks );
if( $pollret == -1 and $! == EINTR or
$pollret == 0 and $self->{sigproxy} ) {
local $!;
@pollmasks = %{ $self->{pollmask} };
my $secondattempt = IO::Poll::_poll( $msec, @pollmasks );
$pollret = $secondattempt if $secondattempt > 0;
}
}
else {
# Workaround - we'll use select to fake a millisecond-accurate sleep
$pollret = select( undef, undef, undef, $timeout );
}
return undef unless defined $pollret;
$self->{pollevents} = { @pollmasks };
return $self->post_poll;
}
}
local/lib/perl5/IO/Async/Loop/Select.pm view on Meta::CPAN
# BITWISE operations
$$readref |= $self->{rvec};
$$writeref |= $self->{wvec};
$$exceptref |= $self->{evec};
$self->_adjust_timeout( $timeref );
$$timeref = 0 if FAKE_ISREG_READY and length $self->{avec};
# Round up to nearest millisecond
if( $$timeref ) {
my $mils = $$timeref * 1000;
my $fraction = $mils - int $mils;
$$timeref += ( 1 - $fraction ) / 1000 if $fraction;
}
return;
}
=head2 post_select
local/lib/perl5/IO/Async/LoopTests.pm view on Meta::CPAN
=head1 DESCRIPTION
This module contains a collection of test functions for running acceptance
tests on L<IO::Async::Loop> subclasses. It is provided as a facility for
authors of such subclasses to ensure that the code conforms to the Loop API
required by L<IO::Async>.
=head1 TIMING
Certain tests require the use of timers or timed delays. Normally these are
counted in units of seconds. By setting the environment variable
C<TEST_QUICK_TIMERS> to some true value, these timers run 10 times quicker,
being measured in units of 0.1 seconds instead. This value may be useful when
running the tests interactively, to avoid them taking too long. The slower
timers are preferred on automated smoke-testing machines, to help guard
against false negatives reported simply because of scheduling delays or high
system load while testing.
TEST_QUICK_TIMERS=1 ./Build test
=cut
=head1 FUNCTIONS
local/lib/perl5/IO/Async/LoopTests.pm view on Meta::CPAN
}
sub time_between(&$$$)
{
my ( $code, $lower, $upper, $name ) = @_;
my $start = time;
$code->();
my $took = ( time - $start ) / AUT;
cmp_ok( $took, '>=', $lower, "$name took at least $lower seconds" ) if defined $lower;
cmp_ok( $took, '<=', $upper * 3, "$name took no more than $upper seconds" ) if defined $upper;
if( $took > $upper and $took <= $upper * 3 ) {
diag( "$name took longer than $upper seconds - this may just be an indication of a busy testing machine rather than a bug" );
}
}
=head1 TEST SUITES
The following test suite names exist, to be passed as a name in the C<@tests>
argument to C<run_tests>:
=cut
local/lib/perl5/IO/Async/LoopTests.pm view on Meta::CPAN
# poll might have returned just a little early, such that the TimerQueue
# doesn't think anything is ready yet. We need to handle that case.
while( !$done ) {
die "It should have been ready by now" if( time - $now > 5 * AUT );
$loop->loop_once( 0.1 * AUT );
}
} 1.5, 2.5, 'loop_once(5) while waiting for timer';
SKIP: {
skip "Unable to handle sub-second timers accurately", 3 unless $loop->_CAN_SUBSECOND_ACCURATELY;
# Check that short delays are achievable in one ->loop_once call
foreach my $delay ( 0.001, 0.01, 0.1 ) {
my $done;
my $count = 0;
my $start = time;
$loop->enqueue_timer( delay => $delay, code => sub { $done++ } );
while( !$done ) {
$loop->loop_once( 1 );
$count++;
last if time - $start > 5; # bailout
}
is( $count, 1, "One ->loop_once(1) sufficient for a single $delay second timer" );
}
}
$cancelled_fired = 0;
$id = $loop->enqueue_timer( delay => 1 * AUT, code => sub { $cancelled_fired = 1 } );
$loop->cancel_timer( $id );
undef $id;
$loop->loop_once( 2 * AUT );
local/lib/perl5/IO/Async/LoopTests.pm view on Meta::CPAN
kill SIGTERM, $$;
is( $caught, 0, '$caught before ->loop_once' );
$loop->loop_once( 0.1 );
is( $caught, 1, '$caught after ->loop_once' );
kill SIGTERM, $$;
is( $caught, 1, 'second raise is still deferred' );
$loop->loop_once( 0.1 );
is( $caught, 2, '$caught after second ->loop_once' );
is_oneref( $loop, '$loop has refcount 1 before unwatch_signal' );
$loop->unwatch_signal( 'TERM' );
is_oneref( $loop, '$loop has refcount 1 after unwatch_signal' );
my ( $cA, $cB );
my $idA = $loop->attach_signal( TERM => sub { $cA = 1 } );
local/lib/perl5/IO/Async/Notifier.pm view on Meta::CPAN
=item *
L<IO::Async::PID> - event callback on exit of a child process
=item *
L<IO::Async::Process> - start and manage a child process
=back
For more detail, see the SYNOPSIS section in one of the above.
One case where this object class would be used, is when a library wishes to
provide a sub-component which consists of multiple other C<Notifier>
subclasses, such as C<Handle>s and C<Timers>, but no particular object is
suitable to be the root of a tree. In this case, a plain C<Notifier> object
can be used as the tree root, and all the other notifiers added as children of
it.
=cut
local/lib/perl5/IO/Async/Resolver.pm view on Meta::CPAN
Because the system may not provide asynchronous versions of its resolver
functions, this class is implemented using a L<IO::Async::Function> object
that wraps the normal (blocking) functions. In this case, name resolutions
will be performed asynchronously from the rest of the program, but will likely
be done by a single background worker process, so will be processed in the
order they were requested; a single slow lookup will hold up the queue of
other requests behind it. To mitigate this, multiple worker processes can be
used; see the C<workers> argument to the constructor.
The C<idle_timeout> parameter for the underlying L<IO::Async::Function> object
is set to a default of 30 seconds, and C<min_workers> is set to 0. This
ensures that there are no spare processes sitting idle during the common case
of no outstanding requests.
=cut
sub _init
{
my $self = shift;
my ( $params ) = @_;
$self->SUPER::_init( @_ );
local/lib/perl5/IO/Async/Resolver.pm view on Meta::CPAN
Name of the resolution operation to perform. See BUILT-IN RESOLVERS for the
list of available operations.
=item data => ARRAY
Arguments to pass to the resolver function. Exact meaning depends on the
specific function chosen by the C<type>; see BUILT-IN RESOLVERS.
=item timeout => NUMBER
Optional. Timeout in seconds, after which the resolver operation will abort
with a timeout exception. If not supplied, a default of 10 seconds will apply.
=back
On failure, the fail category name is C<resolve>; the details give the
individual resolver function name (e.g. C<getaddrinfo>), followed by other
error details specific to the resolver in question.
->fail( $message, resolve => $type => @details )
=head2 resolve (void)
local/lib/perl5/IO/Async/Resolver.pm view on Meta::CPAN
L<Socket>'s C<getaddrinfo> function for more detail.
=item passive => BOOL
If true, sets the C<AI_PASSIVE> flag. This is provided as a convenience to
avoid the caller from having to import the C<AI_PASSIVE> constant from
C<Socket>.
=item timeout => NUMBER
Time in seconds after which to abort the lookup with a C<Timed out> exception
=back
On success, the future will yield the result as a list of HASH references;
each containing one result. Each result will contain fields called C<family>,
C<socktype>, C<protocol> and C<addr>. If requested by C<AI_CANONNAME> then the
C<canonname> field will also be present.
On failure, the detail field will give the error number, which should match
one of the C<Socket::EAI_*> constants.
local/lib/perl5/IO/Async/Resolver.pm view on Meta::CPAN
=item dgram => BOOL
If true, set the C<NI_NUMERICHOST>, C<NI_NUMERICSERV> or C<NI_DGRAM> flags.
=item numeric => BOOL
If true, sets both C<NI_NUMERICHOST> and C<NI_NUMERICSERV> flags.
=item timeout => NUMBER
Time in seconds after which to abort the lookup with a C<Timed out> exception
=back
On failure, the detail field will give the error number, which should match
one of the C<Socket::EAI_*> constants.
->fail( $message, resolve => getnameinfo => $eai_errno )
As a specific optimisation, this method will try to perform a lookup of
numeric values synchronously, rather than asynchronously, if both the
local/lib/perl5/IO/Async/Stream.pm view on Meta::CPAN
the next call, the next time more data is received from the handle.
In this way, it is easy to implement code that reads records of some form when
completed, but ignores partially-received records, until all the data is
present. If the handler is confident no more useful data remains, it should
return C<0>. If not, it should return C<1>, and the handler will be called
again. This makes it easy to implement code that handles multiple incoming
records at the same time. See the examples at the end of this documentation
for more detail.
The second argument is a scalar indicating whether the stream has reported an
end-of-file (EOF) condition. A reference to the buffer is passed to the
handler in the usual way, so it may inspect data contained in it. Once the
handler returns a false value, it will not be called again, as the handle is
now at EOF and no more data can arrive.
The C<on_read> code may also dynamically replace itself with a new callback
by returning a CODE reference instead of C<0> or C<1>. The original callback
or method that the object first started with may be restored by returning
C<undef>. Whenever the callback is changed in this way, the new code is called
again; even if the read buffer is currently empty. See the examples at the end
local/lib/perl5/IO/Async/Stream.pm view on Meta::CPAN
$data = $encoding->encode( $data );
}
$head->data = $data;
next;
}
else {
die "Unsure what to do with reference ".ref($head->data)." in write queue";
}
}
my $second;
while( $second = $writequeue->[1] and
!ref $second->data and
$head->writelen == $second->writelen and
!$head->on_write and !$second->on_write and
!$head->on_flush ) {
$head->data .= $second->data;
$head->on_write = $second->on_write;
$head->on_flush = $second->on_flush;
splice @$writequeue, 1, 1, ();
}
die "TODO: head data does not contain a plain string" if ref $head->data;
if( $IO::Async::Debug::DEBUG > 1 ) {
my $data = substr $head->data, 0, $head->writelen;
$self->debug_printf( "WRITE len=%d", length $data );
IO::Async::Debug::log_hexdump( $data ) if $IO::Async::Debug::DEBUG_FLAGS{Sw};
}
local/lib/perl5/IO/Async/Test.pm view on Meta::CPAN
=head2 wait_for
wait_for { COND }
Repeatedly call the C<loop_once> method on the underlying loop (given to the
C<testing_loop> function), until the given condition function callback
returns true.
To guard against stalled scripts, if the loop indicates a timeout for 10
consequentive seconds, then an error is thrown.
=cut
sub wait_for(&)
{
my ( $cond ) = @_;
my ( undef, $callerfile, $callerline ) = caller;
my $timedout = 0;
my $timerid = $loop->watch_time(
after => 10,
code => sub { $timedout = 1 },
);
$loop->loop_once( 1 ) while !$cond->() and !$timedout;
if( $timedout ) {
die "Nothing was ready after 10 second wait; called at $callerfile line $callerline\n";
}
else {
$loop->unwatch_time( $timerid );
}
}
=head2 wait_for_stream
wait_for_stream { COND } $handle, $buffer
local/lib/perl5/IO/Async/Timer/Countdown.pm view on Meta::CPAN
=head1 PARAMETERS
The following named parameters may be passed to C<new> or C<configure>:
=head2 on_expire => CODE
CODE reference for the C<on_expire> event.
=head2 delay => NUM
The delay in seconds after starting the timer until it expires. Cannot be
changed if the timer is running. A timer with a zero delay expires
"immediately".
=head2 remove_on_expire => BOOL
Optional. If true, remove this timer object from its parent notifier or
containing loop when it expires. Defaults to false.
Once constructed, the timer object will need to be added to the C<Loop> before
it will work. It will also need to be started by the C<start> method.
local/lib/perl5/IO/Async/Timer/Countdown.pm view on Meta::CPAN
=head1 EXAMPLES
=head2 Watchdog Timer
Because the C<reset> method restarts a running countdown timer back to its
full period, it can be used to implement a watchdog timer. This is a timer
which will not expire provided the method is called at least as often as it
is configured. If the method fails to be called, the timer will eventually
expire and run its callback.
For example, to expire an accepted connection after 30 seconds of inactivity:
...
on_accept => sub {
my ( $newclient ) = @_;
my $watchdog = IO::Async::Timer::Countdown->new(
delay => 30,
on_expire => sub {
local/lib/perl5/IO/Async/Timer/Countdown.pm view on Meta::CPAN
start_some_operation(
on_complete => sub { $self->start },
);
},
);
$timer->start;
$loop->add( $timer );
This example invokes the C<start_some_operation> function 60 seconds after the
previous iteration has indicated it has finished.
=head1 AUTHOR
Paul Evans <leonerd@leonerd.org.uk>
=cut
0x55AA;
local/lib/perl5/IO/Async/Timer/Periodic.pm view on Meta::CPAN
=head1 PARAMETERS
The following named parameters may be passed to C<new> or C<configure>:
=head2 on_tick => CODE
CODE reference for the C<on_tick> event.
=head2 interval => NUM
The interval in seconds between invocations of the callback or method. Cannot
be changed if the timer is running.
=head2 first_interval => NUM
Optional. If defined, the interval in seconds after calling the C<start>
method before the first invocation of the callback or method. Thereafter, the
regular C<interval> will be used. If not supplied, the first interval will be
the same as the others.
Even if this value is zero, the first invocation will be made asynchronously,
by the containing C<Loop> object, and not synchronously by the C<start> method
itself.
=head2 reschedule => STRING
local/lib/perl5/Module/Build.pm view on Meta::CPAN
help testdb
html testpod
install testpodcoverage
installdeps versioninstall
You can run the 'help' action for a complete list of actions.
=head1 GUIDE TO DOCUMENTATION
The documentation for C<Module::Build> is broken up into sections:
=over
=item General Usage (L<Module::Build>)
This is the document you are currently reading. It describes basic
usage and background information. Its main purpose is to assist the
user who wants to learn how to invoke and control C<Module::Build>
scripts at the command line.
local/lib/perl5/Module/Build.pm view on Meta::CPAN
=head1 ACTIONS
There are some general principles at work here. First, each task when
building a module is called an "action". These actions are listed
above; they correspond to the building, testing, installing,
packaging, etc., tasks.
Second, arguments are processed in a very systematic way. Arguments
are always key=value pairs. They may be specified at C<perl Build.PL>
time (i.e. C<perl Build.PL destdir=/my/secret/place>), in which case
their values last for the lifetime of the C<Build> script. They may
also be specified when executing a particular action (i.e.
C<Build test verbose=1>), in which case their values last only for the
lifetime of that command. Per-action command line parameters take
precedence over parameters specified at C<perl Build.PL> time.
The build process also relies heavily on the C<Config.pm> module.
If the user wishes to override any of the
values in C<Config.pm>, she may specify them like so:
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
writing a custom Module::Build subclass and have a bootstrapping
problem--that is, your subclass requires modules that may not be
installed when C<perl Build.PL> is executed, but you've listed in
L</build_requires> so that they should be available when C<./Build> is
executed.
=item build_requires
[version 0.07]
Modules listed in this section are necessary to build and install the
given module, but are not necessary for regular usage of it. This is
actually an important distinction - it allows for tighter control over
the body of installed modules, and facilitates correct dependency
checking on binary/packaged distributions of the module.
See the documentation for L<Module::Build::Authoring/"PREREQUISITES">
for the details of how requirements can be specified.
=item configure_requires
[version 0.30]
Modules listed in this section must be installed I<before> configuring
this distribution (i.e. before running the F<Build.PL> script).
This might be a specific minimum version of C<Module::Build> or any
other module the F<Build.PL> needs in order to do its stuff. Clients
like C<CPAN.pm> or C<CPANPLUS> will be expected to pick
C<configure_requires> out of the F<META.yml> file and install these
items before running the C<Build.PL>.
Module::Build may automatically add itself to configure_requires.
See L</auto_configure_requires> for details.
See the documentation for L<Module::Build::Authoring/"PREREQUISITES">
for the details of how requirements can be specified.
=item test_requires
[version 0.4004]
Modules listed in this section must be installed before testing the distribution.
See the documentation for L<Module::Build::Authoring/"PREREQUISITES">
for the details of how requirements can be specified.
=item create_packlist
[version 0.28]
If true, this parameter tells Module::Build to create a F<.packlist>
file during the C<install> action, just like C<ExtUtils::MakeMaker> does.
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
[version 0.3604]
A list of directories can be supplied using an anonymous array
reference of strings.
=item conflicts
[version 0.07]
Modules listed in this section conflict in some serious way with the
given module. C<Module::Build> (or some higher-level tool) will
refuse to install the given module if the given module/version is also
installed.
See the documentation for L<Module::Build::Authoring/"PREREQUISITES">
for the details of how requirements can be specified.
=item create_license
[version 0.31]
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
create a separate F<INSTALL> file if that information isn't in the
generated F<README>.
=item dist_abstract
[version 0.20]
This should be a short description of the distribution. This is used when
generating metadata for F<META.yml> and PPD files. If it is not given
then C<Module::Build> looks in the POD of the module from which it gets
the distribution's version. If it finds a POD section marked "=head1
NAME", then it looks for the first line matching C<\s+-\s+(.+)>,
and uses the captured text as the abstract.
=item dist_author
[version 0.20]
This should be something like "John Doe <jdoe@example.com>", or if
there are multiple authors, an anonymous array of strings may be
specified. This is used when generating metadata for F<META.yml> and
PPD files. If this is not specified, then C<Module::Build> looks at
the module from which it gets the distribution's version. If it finds
a POD section marked "=head1 AUTHOR", then it uses the contents of
this section.
=item dist_name
[version 0.11]
Specifies the name for this distribution. Most authors won't need to
set this directly, they can use C<module_name> to set C<dist_name> to
a reasonable default. However, some agglomerative distributions like
C<libwww-perl> or C<bioperl> have names that don't correspond directly
to a module name, so C<dist_name> can be set independently.
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
A boolean flag indicating whether the F<Build.PL> file must be
executed, or whether this module can be built, tested and installed
solely from consulting its metadata file. The main reason to set this
to a true value is that your module performs some dynamic
configuration as part of its build/install process. If the flag is
omitted, the F<META.yml> spec says that installation tools should
treat it as 1 (true), because this is a safer way to behave.
Currently C<Module::Build> doesn't actually do anything with this flag
- it's up to higher-level tools like C<CPAN.pm> to do something useful
with it. It can potentially bring lots of security, packaging, and
convenience improvements.
=item extra_compiler_flags
=item extra_linker_flags
[version 0.19]
These parameters can contain array references (or strings, in which
case they will be split into arrays) to pass through to the compiler
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
Also see the C<create_license> parameter.
=item meta_add
[version 0.28]
A hash of key/value pairs that should be added to the F<META.yml> file
during the C<distmeta> action. Any existing entries with the same
names will be overridden.
See the L</"MODULE METADATA"> section for details.
=item meta_merge
[version 0.28]
A hash of key/value pairs that should be merged into the F<META.yml>
file during the C<distmeta> action. Any existing entries with the
same names will be overridden.
The only difference between C<meta_add> and C<meta_merge> is their
behavior on hash-valued and array-valued entries: C<meta_add> will
completely blow away the existing hash or array value, but
C<meta_merge> will merge the supplied data into the existing hash or
array value.
See the L</"MODULE METADATA"> section for details.
=item module_name
[version 0.03]
The C<module_name> is a shortcut for setting default values of
C<dist_name> and C<dist_version_from>, reflecting the fact that the
majority of CPAN distributions are centered around one "main" module.
For instance, if you set C<module_name> to C<Foo::Bar>, then
C<dist_name> will default to C<Foo-Bar> and C<dist_version_from> will
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
[version 0.19]
Just like C<pm_files>, but used for specifying the set of C<.pod>
files in your distribution.
=item recommends
[version 0.08]
This is just like the L</requires> argument, except that modules listed
in this section aren't essential, just a good idea. We'll just print
a friendly warning if one of these modules aren't found, but we'll
continue running.
If a module is recommended but not required, all tests should still
pass if the module isn't installed. This may mean that some tests
may be skipped if recommended dependencies aren't present.
Automated tools like CPAN.pm should inform the user when recommended
modules aren't installed, and it should offer to install them if it
wants to be helpful.
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
=item requires
[version 0.07]
An optional C<requires> argument specifies any module prerequisites
that the current module depends on.
One note: currently C<Module::Build> doesn't actually I<require> the
user to have dependencies installed, it just strongly urges. In the
future we may require it. There's also a L</recommends> section for
things that aren't absolutely required.
Automated tools like CPAN.pm should refuse to install a module if one
of its dependencies isn't satisfied, unless a "force" command is given
by the user. If the tools are helpful, they should also offer to
install the dependencies.
A synonym for C<requires> is C<prereq>, to help succour people
transitioning from C<ExtUtils::MakeMaker>. The C<requires> term is
preferred, but the C<prereq> term will remain valid in future
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
C<new()> method is only called once, when the user runs C<perl Build.PL>.
Thereafter, when the user runs C<Build test> or another action, the
C<Module::Build> object is created using the C<resume()> method to
re-instantiate with the settings given earlier to C<new()>.
=item subclass()
[version 0.06]
This creates a new C<Module::Build> subclass on the fly, as described
in the L<Module::Build::Authoring/"SUBCLASSING"> section. The caller
must provide either a C<class> or C<code> parameter, or both. The
C<class> parameter indicates the name to use for the new subclass, and
defaults to C<MyModuleBuilder>. The C<code> parameter specifies Perl
code to use as the body of the subclass.
=item add_property
[version 0.31]
package 'My::Build';
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
return 0;
},
);
Adds a property to a Module::Build class. Properties are those attributes of a
Module::Build object which can be passed to the constructor and which have
accessors to get and set them. All of the core properties, such as
C<module_name> and C<license>, are defined using this class method.
The first argument to C<add_property()> is always the name of the property.
The second argument can be either a default value for the property, or a list
of key/value pairs. The supported keys are:
=over
=item C<default>
The default value. May optionally be specified as a code reference, in which
case the return value from the execution of the code reference will be used.
If you need the default to be a code reference, just use a code reference to
return it, e.g.:
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
$build->args($key, $value);
This method is the preferred interface for retrieving the arguments passed via
command line options to F<Build.PL> or F<Build>, minus the Module-Build
specific options.
When called in a scalar context with no arguments, this method returns a
reference to the hash storing all of the arguments; in an array context, it
returns the hash itself. When passed a single argument, it returns the value
stored in the args hash for that option key. When called with two arguments,
the second argument is assigned to the args hash under the key passed as the
first argument.
=item autosplit_file($from, $to)
[version 0.28]
Invokes the L<AutoSplit> module on the C<$from> file, sending the
output to the C<lib/auto> directory inside C<$to>. C<$to> is
typically the C<blib/> directory.
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
should really be called something like
C<invoke_actions_unless_already_invoked()> or something, but for
better or worse (perhaps better!) we were still thinking in
C<make>-like dependency terms when we created this method.
See also L<dispatch()|/"dispatch($action, %args)">. The main
distinction between the two is that C<depends_on()> is meant to call
an action from inside another action, whereas C<dispatch()> is meant
to set the very top action in motion.
=item dir_contains($first_dir, $second_dir)
[version 0.28]
Returns true if the first directory logically contains the second
directory. This is just a convenience function because C<File::Spec>
doesn't really provide an easy way to figure this out (but
C<Path::Class> does...).
=item dispatch($action, %args)
[version 0.03]
Invokes the build action C<$action>. Optionally, a list of options
and their values can be passed in. This is equivalent to invoking an
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
system prior to a build, or when compiling data to send for a bug
report. The C<prereq_report> action is just a thin wrapper around the
C<prereq_report()> method.
=item prompt($message, $default)
[version 0.12]
Asks the user a question and returns their response as a string. The
first argument specifies the message to display to the user (for
example, C<"Where do you keep your money?">). The second argument,
which is optional, specifies a default answer (for example,
C<"wallet">). The user will be asked the question once.
If C<prompt()> detects that it is not running interactively and there
is nothing on STDIN or if the PERL_MM_USE_DEFAULT environment variable
is set to true, the $default will be used without prompting.
To prevent automated processes from blocking, the user must either set
PERL_MM_USE_DEFAULT or attach something to STDIN (this can be a
pipe/file containing a scripted set of answers or /dev/null.)
local/lib/perl5/Module/Build/API.pod view on Meta::CPAN
=item y_n($message, $default)
[version 0.12]
Asks the user a yes/no question using C<prompt()> and returns true or
false accordingly. The user will be asked the question repeatedly
until they give an answer that looks like "yes" or "no".
The first argument specifies the message to display to the user (for
example, C<"Shall I invest your money for you?">), and the second
argument specifies the default answer (for example, C<"y">).
Note that the default is specified as a string like C<"y"> or C<"n">,
and the return value is a Perl boolean value like 1 or 0. I thought
about this for a while and this seemed like the most useful way to do
it.
This method may be called as a class or object method.
=back
local/lib/perl5/Module/Build/Authoring.pod view on Meta::CPAN
$build->dispatch('install');
If any of these steps encounters an error, it will throw a fatal
exception.
You can also pass arguments as part of the build process:
my $build = Module::Build->new(module_name => 'MyModule');
$build->dispatch('build');
$build->dispatch('test', verbose => 1);
$build->dispatch('install', sitelib => '/my/secret/place/');
Building and installing modules in this way skips creating the
C<Build> script.
=head1 MIGRATION
Note that if you want to provide both a F<Makefile.PL> and a
F<Build.PL> for your distribution, you probably want to add the
following to C<WriteMakefile> in your F<Makefile.PL> so that C<MakeMaker>
local/lib/perl5/Module/Build/Base.pm view on Meta::CPAN
my ($files_found, @docs) = (0);
foreach my $class ($self->super_classes) {
(my $file = $class) =~ s{::}{/}g;
# NOTE: silently skipping relative paths if any chdir() happened
$file = $INC{$file . '.pm'} or next;
open(my $fh, '<', $file) or next;
$files_found++;
# Code below modified from /usr/bin/perldoc
# Skip to ACTIONS section
local $_;
while (<$fh>) {
last if /^=head1 ACTIONS\s/;
}
# Look for our action and determine the style
my $style;
while (<$fh>) {
last if /^=head1 /;
local/lib/perl5/Module/Build/Base.pm view on Meta::CPAN
exclude => [ $self->file_qr('\.bat$') ] );
next unless %$files;
my $sub = $self->can("manify_${type}_pods");
$self->$sub( %extra_manify_args ) if defined( $sub );
}
}
sub manify_bin_pods {
my $self = shift;
my %podman_args = (section => 1, @_); # binaries go in section 1
my $files = $self->_find_pods( $self->{properties}{bindoc_dirs},
exclude => [ $self->file_qr('\.bat$') ] );
return unless keys %$files;
my $mandir = File::Spec->catdir( $self->blib, 'bindoc' );
File::Path::mkpath( $mandir, 0, oct(777) );
require Pod::Man;
foreach my $file (sort keys %$files) {
local/lib/perl5/Module/Build/Base.pm view on Meta::CPAN
next if $self->up_to_date( $file, $outfile );
$self->log_verbose("Manifying $file -> $outfile\n");
eval { $parser->parse_from_file( $file, $outfile ); 1 }
or $self->log_warn("Error creating '$outfile': $@\n");
$files->{$file} = $outfile;
}
}
sub manify_lib_pods {
my $self = shift;
my %podman_args = (section => 3, @_); # libraries go in section 3
my $files = $self->_find_pods($self->{properties}{libdoc_dirs});
return unless keys %$files;
my $mandir = File::Spec->catdir( $self->blib, 'libdoc' );
File::Path::mkpath( $mandir, 0, oct(777) );
require Pod::Man;
foreach my $file (sort keys %$files) {
# Pod::Simple based parsers only support one document per instance.
local/lib/perl5/Module/Build/Base.pm view on Meta::CPAN
my $html = join('',<$fh>);
close $fh;
if (!$self->_is_ActivePerl) {
# These fixups are already done by AP::DT:P:pod2html
# The output from pod2html is NOT XHTML!
# IE6+ will display content that is not valid for DOCTYPE
$html =~ s#^<!DOCTYPE .*?>#<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">#im;
$html =~ s#<html xmlns="http://www.w3.org/1999/xhtml">#<html>#i;
# IE6+ will not display local HTML files with strict
# security without this comment
$html =~ s#<head>#<head>\n<!-- saved from url=(0017)http://localhost/ -->#i;
}
# Fixup links that point to our temp blib
$html =~ s/\Q$blibdir\E//g;
open($fh, '>', $outfile) or die "Can't write $outfile: $!";
print $fh $html;
close $fh;
unlink($tmpfile);
}
local/lib/perl5/Module/Build/Base.pm view on Meta::CPAN
$most_recent_source = -M _ if -M _ < $most_recent_source;
}
foreach my $derived (@$derived) {
return 0 if -M $derived > $most_recent_source;
}
return 1;
}
sub dir_contains {
my ($self, $first, $second) = @_;
# File::Spec doesn't have an easy way to check whether one directory
# is inside another, unfortunately.
($first, $second) = map File::Spec->canonpath($_), ($first, $second);
my @first_dirs = File::Spec->splitdir($first);
my @second_dirs = File::Spec->splitdir($second);
return 0 if @second_dirs < @first_dirs;
my $is_same = ( $self->_case_tolerant
? sub {lc(shift()) eq lc(shift())}
: sub {shift() eq shift()} );
while (@first_dirs) {
return 0 unless $is_same->(shift @first_dirs, shift @second_dirs);
}
return 1;
}
1;
__END__
=head1 NAME
local/lib/perl5/Module/Build/Bundling.pod view on Meta::CPAN
B<WARNING -- THIS IS AN EXPERIMENTAL FEATURE>
In order to install a distribution using Module::Build, users must
have Module::Build available on their systems. There are two ways
to do this. The first way is to include Module::Build in the
C<configure_requires> metadata field. This field is supported by
recent versions L<CPAN> and L<CPANPLUS> and is a standard feature
in the Perl core as of Perl 5.10.1. Module::Build now adds itself
to C<configure_requires> by default.
The second way supports older Perls that have not upgraded CPAN or
CPANPLUS and involves bundling an entire copy of Module::Build
into the distribution's C<inc/> directory. This is the same approach
used by L<Module::Install>, a modern wrapper around ExtUtils::MakeMaker
for Makefile.PL based distributions.
The "trick" to making this work for Module::Build is making sure the
highest version Module::Build is used, whether this is in C<inc/> or
already installed on the user's system. This ensures that all necessary
features are available as well as any new bug fixes. This is done using
the experimental L<inc::latest> module, available on CPAN.
local/lib/perl5/Module/Build/Cookbook.pm view on Meta::CPAN
my $self = shift;
$self->depends_on("test");
$self->do_system(qw(svn commit));
}
SUBCLASS
=head2 Bundling Module::Build
Note: This section probably needs an update as the technology improves
(see contrib/bundle.pl in the distribution).
Suppose you want to use some new-ish features of Module::Build,
e.g. newer than the version of Module::Build your users are likely to
already have installed on their systems. The first thing you should
do is set C<configure_requires> to your minimum version of
Module::Build. See L<Module::Build::Authoring>.
But not every build system honors C<configure_requires> yet. Here's
how you can ship a copy of Module::Build, but still use a newer
local/lib/perl5/Struct/Dumb.pm view on Meta::CPAN
Takes the following options:
=over 4
=item named_constructor => BOOL
Determines whether the structure will take positional or named arguments.
=item predicate => STR
If defined, gives the name of a second function to export to the caller's
namespace. This function will be a type test predicate; that is, a function
that takes a single argmuent, and returns true if-and-only-if that argument is
an instance of this structure type.
=back
=cut
=head2 readonly_struct
local/lib/perl5/Test/Exception.pm view on Meta::CPAN
throws_ok BLOCK CLASS, TEST_DESCRIPTION
In the first form the test passes if the stringified exception matches the give regular expression. For example:
throws_ok { read_file( 'unreadable' ) } qr/No file/, 'no file';
If your perl does not support C<qr//> you can also pass a regex-like string, for example:
throws_ok { read_file( 'unreadable' ) } '/No file/', 'no file';
The second form of throws_ok() test passes if the exception is of the same class as the one supplied, or a subclass of that class. For example:
throws_ok { $foo->bar } "Error::Simple", 'simple error';
Will only pass if the C<bar> method throws an Error::Simple exception, or a subclass of an Error::Simple exception.
You can get the same effect by passing an instance of the exception you want to look for. The following is equivalent to the previous example:
my $SIMPLE = Error::Simple->new;
throws_ok { $foo->bar } $SIMPLE, 'simple error';