in reply to Complicated Search and Replace

Here's another solution:

use strict; use warnings; while ( <DATA> ) { my ( $args ) = /\@MAC\((.*)\)/; my ( $lhs, $v0, $v1, $e ) = split /,/, $args; print "$lhs=\n", term( $v0, $v1, [0..$e-1] ), "\n"; } sub term { my $indices = pop; my $n = $#$indices; if ( $n ) { my $m = int($n/2); my @t = map term( @_, $_ ), [ @{$indices}[0..$m] ], [ @{$indices}[$m+1..$n] ]; return "($t[0])+($t[1])"; } else { my ( $v0, $v1 ) = @_; my $first = $indices->[0]; return "$v0$first*$v1$first"; } } __DATA__ @MAC(Result,A,B,2) @MAC(output,X,Y,8) __END__ Result= (A0*B0)+(A1*B1) output= (((X0*Y0)+(X1*Y1))+((X2*Y2)+(X3*Y3)))+(((X4*Y4)+(X5*Y5))+((X6*Y6)+(X7* +Y7)))

the lowliest monk