Dedicated to my comrade-in-obsessing, Limbic~Region (whom I invite to translate this into Perl6).
A seldom-used feature of glob is that it acts as an iterator when in scalar context. Here's how to use it as the workhorse for generating a powerset iteratively. To avoid any special characters showing up in the glob string, the actual values are put in an array, and the indices are used in the glob string. The "+" char is used as a separator. To extract the elements, the string returned from glob is split on + and used to index the array.

Using this technique, the task of creating an iterator boils down to creating a glob string.

# This one constructs a simple glob and returns the sub that will # iterate through it. sub iter_powerset { my @elems = @_; my $glob_str = join 'X', map {"{$_,}"} 0..$#elems; sub { @elems[grep length, split 'X', scalar glob $glob_str] }; } # This is an auxiliary to iter_powerset2 (below). The glob expression +is # more complex, in order to get the desired order of output. As the nu +mber # of elements grows, the glob string balloons, quickly becoming too la +rge # to work. sub powerset_glob { my ($car, @cdr) = @_; if (@cdr) { my $cdr_globstr = powerset_glob(@cdr); return (join ',', "{$car", "$car+$cdr_globstr", "$cdr_globstr}"); } else { return $car } } # Call the glob string builder and return the iterator subroutine sub iter_powerset2 { my @elems = @_; my $glob_str = powerset_glob(0..$#elems); sub { @elems[grep length, split /\+/, scalar glob $glob_str] }; } # Demonstration code. Call either iter_powerset function my $iter = iter_powerset2(2,3,5,7); while (my @set = $iter->()) { print "<@set>\n"; }

In reply to Glob powerset with progressive ordering by Roy Johnson

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.