Listing 1: Translating parenthetical expressions from C to English. Converting C to English with Perl
The Perl Journal, Fall 2000
 
 


primary_expression :  
    '('
    expression
    ')' 
{
    my $expression = $item{expression}; 
    my $repeats = 1; 
    my $ending = 1; 

    # We use these variables to keep track of layer numbers.
    # If we have an expression that is already nested in the front,
    # we remove the nesting.

    if ($expression =~  /^the (\\d+)-layered parenthetical expression/) { 
        $repeats = $1 + 1; 
        $expression =~ s/^the \\d+-layered parenthetical expression //;

    # If we have to start the nesting, we do this:
    } elsif ($expression =~  /^the parenthetical expression/) { 
        $repeats = 2; 
        $expression =~ s/^the \\d+-layered parenthetical expression //;
    } 

    # So for now the internal parens are gone.
    # Now, to the rear of our expression:
    if ($expression =~ / now$/) { 
        $ending ++; 
        $expression =~ s/ now$//; 
        $expression .= " (now drop $ending layers of context)"; 
    } elsif ($expression =~ /now drop (\\d+) layers of context\)$/ ) { 
        $ending =~ $1 +1; 
        $expression =~ s/\\d+ layers of context\)$/$ending layers of context \)/; 
    } else { $expression .= ' now'; } 

    # Finally, we wrap the expression in our pair of parens:
    if ($repeats > 1) { 
        $return = "the $repeats-layered parenthetical expression $expression"; 
    } else { 
        $return = "the parenthetical expression $expression"; 
    }

    # And one more detail: if we're closing the parentheses at the very
    # end of the C statement, we don't need to bother with the word "now."
    if ($text =~ /^;/) {
        $return =~ s/ now$//;
    } 
}