$_=join("",<>); s/\[(.+?)\]/"(" . join("|", split(m||, $1)) . ")"/eg; s/(^|\)|\?)(\w+)(?!\?)/$1($2)/g; s/(\w+)\?/($1)\?/g; s/\(([^\(\)]+)\)\?/(|$1)/g; s/\(([^\(\)]+)\)/push(@e, [split(m!\|!, $1)])/eg; @o = (""); for $aref (@e){ @n = (); for $lh (@o){ push @n, $lh . $_ for @$aref } @o = @n; } print $_ . $/ for @o