Re: Perl Quiz of the Week #23
Joe Schaefer <joe+gmane-spy1PHYPFi+U+1/[email protected]>
| Newsgroups | gmane.comp.lang.perl.qotw.discuss |
|---|---|
| Message-ID | <[email protected]> |
Mark Jason Dominus <[email protected]> writes: [...] > Write a program, 'parens', which gets a command line argument, n', > which is an integer. The program should print all the > properly-balanced strings of parentheses of length 2n. For example, > given the argument '3', the program should print these five lines: Here's a recursive solution using the regexp engine. Basically I thought of a line like (()(())) as being a regexp match by inserting an "x" after each "(" (x(x)(x(x))) Then I adapted the balanced parens pattern in perlre to this particular problem, using $^R to keep track of the pattern match. #!/usr/bin/perl -l # Usage: perl qotw23.pl n - generate list of balanced parens of length 2n use re 'eval'; $r = qr/ (?{ "$^R(" }) # insert "(" before first matching "x" (x(??{$r})* ) # actual (recursive) pattern (?{ "$^R)" }) /x; # insert ")" after final matching "x" /^$r*$(??{print $^R})/ for "x" x shift; -- Joe Schaefer