use strict; use warnings; my $eq = '2+3x+7x(x+27)-6'; my @mult=(1); my @pow=(0); my @c; # die "Not supported.\n" if /[^-+0-9x]/; die "Not supported: '$1' \n" if $eq =~ /([^-+0-9x()]+)/; # as per AnomalousMonk's suggestion print "Equation: $eq\n"; while($eq=~/([-+]?)(\d*)(x?)([)(]?)/g){ next unless "$1$2$3$4"; my $d = $2 || 1; $d *= -1 if $1 eq '-'; if( $4 eq '(' ) { push @mult, $mult[-1]*$d; push @pow, $pow[-1]+1; } else { if( $3 ) { $c[1+$pow[-1]] += $mult[-1]*$d; } else { $c[$pow[-1]] += $mult[-1]*$d; } } if( $4 eq ')' ) { pop @mult; pop @pow; } } print "Summary: @c\n";