Daniel D Jones wrote:
> Given something like the following:
>
> my @variables = [3, 7, 13, 4, 12];

You want round brackets here. You've created an array with just one element, with a reference to an anonymous array as its value.

> my @tests = ("2*a+b==c", "c-d+a==e");
>
> I need to be able to evaluate the mathematical truth of the tests, using the
> values from @variables, where $variable[0] holds the value of the
> variable 'a', $variables[1] holds the value of 'b', etc.  I can do the
> evaluation but how do I (reasonably efficiently) substitute the values into
> the strings?  (The length of the array and the exact tests are not known
> until run time.)
>
> In C, I'd do this by walking through the test strings character by character,
> checking for isalpha, converting the character to its ascii value and
> subtracting the ascii value of 'a', and indexing into the array.  In Perl I'm
> not sure how to do this type of low level character by character processing.
> The only thing which occurs to me is to split() the string into an array of
> characters, then walk through that array.  Am I on the right track or is
> there an easier way to do this in Perl?

Hi Daniel.

You can do exactly that in Perl, and a lot more simply:

  my @variables = (3, 7, 13, 4, 12);
  my @tests = ("2*a+b==c", "c-d+a==e");

  foreach (@tests) {
    s/([a-z])/$variables[ord($1) - ord('a')]/ge;
    print $_, "\n";
  }

OUTPUT

  2*3+7==13
  13-4+3==12

HTH,

Rob

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to