• stateful recursion for list expansion

    From Rainer Weikusat@21:1/5 to All on Fri Nov 3 14:37:34 2023
    Problem: Turn a list of filehandles which may or may not be followed by
    an poll (system call) event specification into a list of triples

    <file descriptor>, <event spec>, 0

    which can be used as input to a pack call generating a struct pollfd
    array which can be used as input to poll. If there's no event
    specification for a filehandle, POLLIN is supposed to be used for it.

    After various attempts which all had much too much duplicated code, I
    came up with the following, statefully recursive solution:

    sub build_pfds
    {
    return pack('('.PFD.')*', &expand_fh);
    }

    sub expand_fh
    {
    return unless @_;
    return (fileno(shift), &expand_ev);
    }

    sub expand_ev
    {
    my $ev;

    $ev = @_ && !defined(reftype($_[0])) ? shift : POLLIN;
    return ($ev, 0, &expand_fh);
    }

    I'd be very much interested in opinions on that.

    PFD is a constant defined as 'iss', the layout of a struct pollfd.

    The caller is responsible for providing a well-formed argument list, ie,
    glob references optionally interspersed with event specifications ---
    I'm not in the "must defend against buggy code written by other
    people" camp.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)