#!/usr/bin/perl use strict; chomp (my $equation = ); my @stack; foreach ( split(/\s*,\s*/, $equation) ) { push(@stack,$_), next if /\d+/; die "stack underrun" if @stack < 2; my ($val1, $val2) = (pop(@stack), pop(@stack)); push(@stack, $val1 + $val2), next if $_ eq '+'; push(@stack, $val1 * $val2), next if $_ eq 'x'; die "undef. operator ($_)"; } print "Result (stack): ", join(", ", @stack), "\n"; __DATA__ 1,2,3,4,+,5,+,x,6, ...... x,x,x,x,x,9164,x,+,9165,9166,91 <--- your input as a single line Result (stack): 1, 144, 1.9792773969506e+27, 6.22437334578068e+26, 5.77209920038837e+273, 8966, 4.97957520221034e+261, 9165, 9166, 91