PerlJam2015 has asked for the wisdom of the Perl Monks concerning the following question:
I'm quite new to Perl, and I'm writing a script to use Simpson's Rule to evaluate integrals numerically over closed intervals (The homework is to do it by paper, and the instructor will allow me to use programs to do the work if I write it myself since it is INCREDIBLY tedious and he states it is best left to computers) and coming to the realization that I don't how to take user input of a function f(x) in the form "argumentx" such as "1/x" or "3-x" or "(1-x)/(sin**2(2x)" and turn that into a subroutine which would then work over any defined x.
The workaround is to write the function into the code as a subroutine, but what I was thinking is that if the proper amount of parenthesis were used, then the user could enter the argument in that format and then I could search-and-replace any literal 'x' with '@_'.
I'm getting a little lost in this thought process, and I'm sure someone has already done this much. I'll be playing around with it more, but I'm curious if anyone knows if the search-and-replace approach would result in obvious problems.
So far, I have this...
use warnings; use strict; #Take any function input in the correct format, and turn it into a sub +routine. print "Enter a function in the 'expression(x)' format"; chomp(my $function = <STDIN>); $function = s/x/@_/g sub function{ $function; } my $tobedone = 53; #Example number my $done = &function($tobedone);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: An Approach to Function to Subroutine using Regular Expression
by BrowserUk (Patriarch) on Feb 22, 2015 at 02:50 UTC | |
|
Re: An Approach to Function to Subroutine using Regular Expression
by LanX (Saint) on Feb 22, 2015 at 04:56 UTC | |
|
Re: An Approach to Function to Subroutine using Regular Expression
by LanX (Saint) on Feb 23, 2015 at 07:32 UTC |