in reply to regex and string functions help needed.

velanvp: I'm not sure the rest of your code does what you want, as your specifications are all over the place. However, near the end, you could try changing this:

my $result = 0; my $temp=0; for my $letter (@letters) { $result=$result + $value{ $letter }* $factor{ $letter }; #print "$result\n"; };

Change $result to be initialized as 1, and change the assignment to $result inside your for loop to use the *= operator. And get rid of $temp - it doesn't look like you're using it. The result will look like this:

my $result = 1; for my $letter (@letters) { $result *= $value{ $letter } * $factor{ $letter }; };

If that doesn't work, or if you're still having trouble understanding what you're doing, see if you can understand the following any easier ( which has been Updated: replaced pop @divisors with shift @divisors, fixed output to match updated code. )

#!/usr/bin/perl use strict; use warnings; sub calc { my $string = shift; my %p = ( A => 1.5, B => 2.5, C => 3.5, ); # in another thread, he indicated this was the series he needed my @divisors = ( 50/100, 55/100, 60/100, 65/100, 70/100, 75/100, 80/100, 85/100, 90/100 ); my $result = 1; # in another thread, he said he needed to match A,B,C,D,E,F,G,H an +d J my @substrings = $string =~ /(\d{0,1}[A-HJ])/g; for( @substrings ){ my $divisor = shift @divisors; my( $exponent, $letter ) = /(\d){0,1}([A-HJ])/; $exponent ||= 1; $result *= $p{ $letter } ** $exponent * $divisor; } return $result; } for( qw( 2A 2B 2A2B2C 4ABC 4AC ABC BC ) ){ print "string: $_\n"; my $result = calc( $_ ); print "result: $result\n\n"; }
Output:
string: 2A result: 1.125 string: 2B result: 3.125 string: 2A2B2C result: 28.423828125 string: 4ABC result: 7.308984375 string: 4AC result: 4.87265625 string: ABC result: 2.165625 string: BC result: 2.40625

Same idea as everyone else, and also seems to give you some of your desired output (at least for the values of A, B, and C that you posted earlier - I believe your expected output above is using your earlier values, not 2.74, 2.65, and 2.5 as above).

However, having said that - if this still doesn't satisfy your requirements, you really need to give us crystal clear requirements - because right now, we're working from a bare minimum. I'm sure you know what you mean, but we apparently do not. Start simple, like:

Divisors: 50/100, 55/100, 60/100
Values: A = 2, B = 3, C = 4.
String: 2A
Equation: ( A * A ) * ( 50 / 100 )
Output: 2

String: 3A
Equation: ( A * A * A ) * 50 / 100
Output: 4

String: 2A2B
Equation: ( ( A * A ) * ( 50 / 100 ) ) * ( ( B * B ) * ( 55 / 100 ) )
Output: 9.9

And then maybe introduce a few more advanced examples.



--chargrill
s**lil*; $*=join'',sort split q**; s;.*;grr; &&s+(.(.)).+$2$1+; $; = qq-$_-;s,.*,ahc,;$,.=chop for split q,,,reverse;print for($,,$;,$*,$/)

Replies are listed 'Best First'.
Re^2: regex and string functions help needed.
by holli (Abbot) on Oct 26, 2006 at 06:35 UTC