October 2012 Archives

A little “state” idiom

    # ... something that needs to be done twice ...

    if ( not state $first_iteration_done++ ) {
        # ... something that must only happen after the first time ...

In general, some form of “if state $flag” can be used as a “have I been here?” idiom that avoids the need to mention the flag’s identifier anywhere else. Without state, one must repeat oneself some distance away at least to declare the flag in whichever outer scope has the appropriate lifetime.

A concise forking idiom in pure Perl

One of the first module I took over as a maintainer on CPAN was Proc::Fork.

It is a beautiful interface.

It did get a bit uglier in relatively recent times when I added the run_fork wrapper, an unfortunate necessity in certain cases.

But for small single-file-redistributable programs that can be offered to people who are merely users of a Unix system, who do not have any sort of CPAN setup or installation experience, it always felt like a burden to pull in a dependency for something as… insubstantial as this little bit of syntactic sugar:

run_fork {
    child {
        # ...
    parent {
        my $kid = shift;
        # ...

Just the other day, it occurred to me that with given/when, it is easy to construct an idiom for forking that is just as concise, if not self-documenting to the same extent:

About Aristotle

user-pic Waxing philosophical