I like this code.

Here are some improvements on the code. The most important is that it can handle negation of numbers, such as (- (+ 1 1)) which evaluates to -2. This version uses the first cmd-line argument as the expression. ;Updates: you notice the lack of spaces, don't you?

#!/usr/bin/perl use strict; use warnings; #use Data::Dumper; my $operators = { 'begin' => sub { pop }, '+' => sub { my $i = 0; $i += $_ for @_; $i; }, '-' => sub { my $i = shift @_; @_ or return -$i; $i -= $_ for @_; +$i; }, '*' => sub { my $i = 1; $i *= $_ for @_; $i; }, '/' => sub { my $i = shift @_; @_ or return 1/$i; $i /= $_ for @_; + $i; }, }; my $task = $ARGV[0]; print calculate( $task =~ m(([\w!$%&*+-./<=>?@^~]+|\S))g ), "\n"; exit; sub solve { my ( $op, @vals ) = @_; die "solve(): wrong operator or to less values" unless ( exists $operators->{$op} ); return $operators->{$op}(@vals); } sub calculate { my @ops = @_; @ops = @ops[ 1 .. $#ops - 1 ] if $ops[0] eq '(' and $ops[-1] eq ')'; # remove leading and trailing brackets my $marker = -1; my $begin = undef; my $end = undef; my @marked = (); for ( 0 .. $#ops ) { $begin = $_ if $ops[$_] eq '(' && ++$marker == 0; $end = $_ if $ops[$_] eq ')' && $marker-- == 0; if ( defined $begin && defined $end ) { push @marked, { begin => $begin, end => $end }; # find balanced brackets on this lev +el $marker = -1; $begin = undef; $end = undef; } } while (@marked) { my $current = pop @marked; splice @ops, $current->{begin}, # recursively solve inner b +rackets $current->{end} - $current->{begin} + 1, calculate( @ops[ $current->{begin} .. $current->{end} ] ); } #print Dumper \@ops; return solve(@ops); } __END__

In reply to Re: Solving lisp-style terms by ambrus
in thread Solving lisp-style terms by neniro

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.