Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: A better way than ||

by fishbot_v2 (Chaplain)
on Dec 31, 2005 at 15:43 UTC ( [id://520156]=note: print w/replies, xml ) Need Help??


in reply to A better way than ||

So, part (all?) of the problem here is that you have an off-by-one error in your array traversal: @weights in scalar context will give you the number of elements in the array, not the last index. Thus you are always falling off the end of your weights array. Change to:

for ( 0..$#weights ) { # ...

You've said that the two arrays have the same number of elements. If they are all defined, always, then you have solved the problem.

If any of them might be undefined (ie. the array is sparse) then you have a different issue, which you probably want to solve the way you supressed the warning above. (or with $weights[$_] ||= 0)

Replies are listed 'Best First'.
Re^2: A better way than ||
by adrianh (Chancellor) on Dec 31, 2005 at 16:26 UTC
    Change to: for ( 0..$#weights )

    Alternatively do away with all that tedious messing around with indices completely :-)

    use List::Util qw( sum ); use List::MoreUtils qw( pairwise ); my $sum = sum pairwise { $a * $b } @weights, @digits;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://520156]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2024-04-26 04:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found