There are many errors or weird things in your program

  1. You are not indenting your code properly so it is very hard to see what loop goes around what code.
  2. Your string expansion is very weird. Why do you expand your string 2A2B2C in a loop when the regular expression already does the complete expansion?
  3. Your string length calculation is wrong. You calculate the length of the unexpanded string 2A2B2C instead of calculating the length of the expanded string. Also, name your length variable something better than $b. Maybe call it $string_length or $sequence_length, so that you and others understand what you are doing.
  4. Your if ... elsif ... structure is very, very bad and error prone. If you want to associate a letter with a value, a hash is the natural structure:
    my %value = ( A => 1.5, B => 2.5, C => 3.5, ); my %factor = ( A => 50/100, B => 55/100, C => 60/100, );

    You can then easily split up your string and calculate the numbers.

    my @letters = split //, $expanded_string; my $result = 0; for my $letter (@letters) { $result = $result + $value{ $letter } * $factor{ $letter }; }; print $result;

With these changes, I get a result of 8.45, so either your calculation of 28.4238 is wrong or you need to explain how you arrive at that number. Basically, my code calculates the following number:

$result = 1.5 * (50/100) * 2 + 2.5 * (55/100) * 2 + 3.5 * (60/100) * 2

In reply to Re: string functions by Corion
in thread string functions by valavanp

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.