0

I´m learning Perl, I would like to surrounded an expression like that

function1(mathematical_expresion1)*function2(mathematical_expresion2)

Where 'function1'and 'function2' could be whatever word and combine numbers inside, for instance function1 could be fun3dec, fun4nels, factor9 or whatever... so my code will became this

surrounded(function1(mathematical_expresion1)*function2(mathematical_expresion2))surroundedend

Where surrounded and surroundedend are string chains.

So if I have an expression like this:

exp(-49/200)-exp(-49/200)*(x-49/200)+1/2*exp(-49/200)*(x-49/200)^2-1/6*exp(-49/200)*(x-49/200)^3+1/24*exp(-49/200)*(x-49/200)^4-1/120*exp(-49/200)*(x-49/200)^5+1/720*exp(-49/200)*(x-49/200)^6-1/5040*exp(-49/200)*(x-49/200)^7+1/40320*exp(-49/200)*(x-49/200)^8-1/362880*exp(-49/200)*(x-49/200)^9+1/3628800*exp(-49/200)*(x-49/200)^10-1/39916800*exp(-49/200)*(x-49/200)^11+1/479001600*exp(-49/200)*(x-49/200)^12

I could surround a all multiplication of two terms in the previous expression.

Thank you for teach me Perl!

Peterstone
  • 7,119
  • 14
  • 41
  • 49
  • can functions be nested? Can multiplications be nested inside functions? can you use additional brackets to surround expressions? – Alex Brown Nov 25 '10 at 14:36

1 Answers1

1

Here's a first (incomplete) solution, that raises some questions about what you want to do:

I have used a simpler syntax for brevity and clarity - arguments to functions are simple digits or expressions. function names are single letters. The surround is replaced by S{}. It's easy to extend from this to your example, though.

sample.txt:

 1  A(1)
 2  A(1)*B(2)
 3  C(2)+A(1)*B(2)
 4  C(A(1)*B(2))
 5  C(A(1)*B(3)+C(4))
 6  A(1)*B(2)+C(3)*D(4)
 7  A(1)*B(2)*C(3)*D(4)
 8  A(B(2)*C(3))*D(4)
 9  C(A(1)+B(3))*C(4)

perl < sample.txt -pe 's/(\w\(\d+\)\*\w\(\d+\))/S{\1}/g'

 1  A(1)
 2  S{A(1)*B(2)}
 3  C(2)+S{A(1)*B(2)}
 4  C(S{A(1)*B(2)})
 5  C(S{A(1)*B(3)}+C(4))
 6  S{A(1)*B(2)}+S{C(3)*D(4)}
 7  S{A(1)*B(2)}*S{C(3)*D(4)}
 8  A(S{B(2)*C(3)})*D(4)
 9  C(A(1)+B(3))*C(4)

So, what should line 7 be doing? What should line 8 be doing?

Line 9 doesn't work because my code isn't smart enough, and I don't know if you NEED it to work.


I suggest that you really need a parser (e.g. yacc) as well as a lexer. Perl has a lexer in it, but not a parser.

The problem here is that you are searching for instances of:

<expression> `*` <expression>

but since expression is defined as

<expression> = \d+
             | <function>
             | <expression> <op> <expression>

You need a push down automaton to make this work correctly. Perl regular expressions just can't do this.

NOTE: it's been a decade since my compiler course, so I may be a bit wobbly in my terminology.

Alex Brown
  • 41,819
  • 10
  • 94
  • 108