The use of a hash in this application is positively dangerous unless the elements of the  @change array (which become the keys of the hash) can be guaranteed to be unique. E.g.:

>perl -wMstrict -le "my @change = (1.15, -0.1, 5.4, 1.03, 1.15, -0.241); my @numberofshares = (9999, 400, 200, 300, 500, 240); my %hash; @hash{@change} = @numberofshares; printf qq{%d keys in hash (oops...) \n}, scalar keys %hash; my $sum = 0; while (my($k, $v) = each %hash) { $sum += $v * $k; } print qq{sum == $sum (?)}; " 5 keys in hash (oops...) sum == 1866.16 (?)

Update: The algorithm can be expressed more concisely with some list-processing functions:

>perl -wMstrict -le "use List::Util qw(sum); use List::MoreUtils qw(pairwise); use vars qw($a $b); my @change = (1.15, -0.1, 5.4, 1.03, -0.241); my @numberofshares = ( 100, 400, 200, 300, 240); my $sum = sum pairwise { $a * $b } @change, @numberofshares; print qq{sum == $sum}; " sum == 1406.16

I think it could be expressed yet more concisely in Perl 6, but my 6-fu is not that great. Would it be something like:
    my $sum +=<<*<< @change, @numberofshares;


In reply to Re: simultaneously adding and multiplying numbers in a hash/ array by AnomalousMonk
in thread simultaneously adding and multiplying numbers in a hash/ array by derpp

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.