The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Attempt - attempt to run code multiple times


  use Attempt;

  # if the database goes away while we're using it, just try again...
  attempt {

    my $dbh = DBI->connect("DBD::Mysql:foo", "mark", "opensaysme")
      or die "Can't connect to database";
    $dbh->{RaiseException} = 1;
    $dbh->do("alter table items change pie pies int(10)");

  } tries => 3, delay => 2;


Attempt creates a new construct for things that you might want to attempt to do more than one time if they throw exceptions, because the problems they throw exceptions to report might go away.

Exports a new construct called attempt. The simplest way to use attempt is to write attempt followed by a block of code to attempt to run.

  attempt {

By default perl will attempt to run to run the code again without delay if an exception is thrown. If on the second run an exception is again thrown, that exception will be propogated out of the attempt block as normal.

The particulars of the run can be changed by passing parameters after the code block. The tries parameter effects the number of times the code will attempt to be run. The delay parameter determines how often perl will wait - sleep - between runs.

attempt can return values, and you can exit out of an attempt block at any point with a return statement as you might expect. List and scalar context is preserved though-out the call to the block.


Written by Mark Fowler <>

Copryright Mark Fowler 2003. All Rights Reserved.

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


Only respects list and scalar context, doesn't replicated the more complicated forms of context that Want supports.

The caller isn't what you might expect from within the attempt block (or rather, it is, but isn't what it would have been if the block wasn't there)

Bugs should be reported to me via the CPAN RT system.


Sub::Attempts, Attribute::Attempts