How do you use IO::Async with a short example?

IO::Async is a Perl module that provides an asynchronous programming framework. It allows you to handle multiple tasks without blocking the execution of your program, making it great for IO-bound applications.

Perl, IO::Async, asynchronous programming, non-blocking IO, Perl modules

This example demonstrates a simple use of IO::Async to create a timer that prints a message every second for five seconds.


use strict;
use warnings;
use IO::Async::Timer::Periodic;
use IO::Async::Loop;

my $loop = IO::Async::Loop->new;

my $timer = IO::Async::Timer::Periodic->new(
    interval => 1,
    on_tick  => sub {
        print "Tick!\n";
    },
);

$loop->add($timer);
$timer->start;

$loop->add(
    IO::Async::Timeout->new(
        after => 5,
        on_timeout => sub {
            print "Stopping the loop after 5 seconds.\n";
            $loop->stop;
        },
    )
);

$loop->run;
    

Perl IO::Async asynchronous programming non-blocking IO Perl modules