# For some time now, symbolic calculation can be carried # out from within Perl: (warning: plug from module author) # # If you find this interesting, check out the module on CPAN # and/or actively help with the development! use strict; use warnings; use Math::Symbolic qw/:all/; my $energy = parse_from_string(<<'HERE'); kinetic(mass, velocity, time) + potential(mass, z, time) HERE $energy->implement(kinetic => '(1/2) * mass * velocity(time)^2'); $energy->implement(potential => 'mass * g * z(t)'); $energy->set_value(g => 9.81); # permanently print "Energy is: $energy\n"; # Is how does the energy change with the height? my $derived = $energy->new('partial_derivative', $energy, 'z') ->apply_derivatives() ->simplify(); print "Changes with the heigth as: $derived\n"; # With whatever values you fancy: print "Putting in some sample values: ", $energy->value(mass => 20, velocity => 10, z => 5), "\n"; # Too slow? $energy->implement(g => '9.81'); # To get rid of the variable my ($sub) = Math::Symbolic::Compiler->compile($energy); print "This was much faster: ", $sub->(20, 10, 5), # vars ordered alphabetically "\n"; # Output: # Energy is: (((1 / 2) * mass) * (velocity ^ 2)) + ((mass * g) * z) # Changes with the heigth as: mass * g # Putting in some sample values: 1981 # This was much faster: 1981