On Saturday 15 July 2006 21:13, Rob Dixon wrote:
> 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.
Doh! Knew that! I have no idea what my fingers are thinking sometimes. :-)
> > 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.)
...
> 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,
It certainly does help. I thought about substitution but couldn't come up
with a syntax. This seems to be exactly what I was looking for, but I'm
running into a problem. Here's code which demonstrates it:
use strict;
my @values = (1..4);
my @tests = ("a+b==c", "2*b==d");
my $size = @values-1;
my $index = $size;
@values = sort @values;
#Generate all possible perms of input array and run test on each one
while($index > -1) {
$index = $size-1;
if(runtests()) {
print @values, "\n\n";
}
$index-- while ($values[$index] > $values[$index+1]);
@values[$index+1..$size] = reverse @values[$index+1..$size];
my $swap= $index+1;
$swap++ while $values[$index] > $values[$swap];
@values[$index,[EMAIL PROTECTED],$index];
}
sub runtests() {
my $testresults = 0;
print "Values inside runtest: @values\n";
foreach my $test (@tests) {
$test =~ s/([a-z])/$values[ord($1) - ord('a')]/g;
$testresults++ if eval $test;
print $test, "\teval: ", $testresults, "\n";
}
print "\n";
return $testresults;
}
The output I get is this:
Values inside runtest: 1 2 3 4
1+2==3 eval: 1
2*2==4 eval: 2
1234
Values inside runtest: 1 2 4 3
1+2==3 eval: 1
2*2==4 eval: 2
1243
Values inside runtest: 1 3 2 4
1+2==3 eval: 1
2*2==4 eval: 2
1324
Values inside runtest: 1 3 4 2
1+2==3 eval: 1
2*2==4 eval: 2
1342
...
As you can see, the @values array is being shuffled to generate the perms
correctly. However, the substitution seems to always be using the original,
unshuffled values. Is it being cached somehow or what?
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>