Hypotheticals in Perl 5

In Appendix C of Apocalypse 12, Larry speculatively mentioned the syntax:

    let foo();

Which would “try” foo, and then revert things back to the way they were before that if something failed in your block. Well, I’ve implemented a Perl 5 module, Data::COW (which hasn’t been indexed at my time of writing, but will be at your time of reading), which could, er, hypothetically let you do that. Interestingly, I implemented it so you could do that on a smaller scale for the logic programming module I’m writing.

First, assume that all external state in your program is accessed through %$state, and everything other than that is purely functional. This seems like a big assumption, and it kind of is, and it kind of isn’t. If you don’t change the state of any modules (a fairly easy thing to do, depending on what modules you’re using), it would be fairly trivial, though maybe not easy easy, to massage all your own state into a single global hash. (Note that all stateful things need not be in the hash: the hash is just your “root set”, corresponding quite closely to all of your globals and file-scoped lexicals.)

Then I can easily write temp foo():

    my $old = $state;
    $state = make_cow_ref $state;
    foo();
    # remaining code in the block
    $state = $old;

foo() is allowed to change whatever it likes, and it will be restored (of course, only those things that can be copied can be restored) after the block ends. let() is approximately the same:

    my $old = $state;
    $state = make_cow_ref $state;
    eval {
        foo();
        # remaining code in block
        1 } or $state = $old;

It’d be sweet if Perl 6 could allow that kind of thing to operate on the global state instead of a single hash. Sweet indeed, but I don’t know how practically useful.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s