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);

In reply to An Approach to Function to Subroutine using Regular Expression by PerlJam2015

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.