The result of $num % 1000000007 will always be $num for all values less than 1000000007. Therefore, if all values in @array are within 0 .. 50 000, such a calculation is redundant. You need to take two steps, and not use the *= operator:
$ans = ($ans % 1000000007) * $_ for @array;
A word of caution. For any non-standard module, there is always a risk that your modulo operation will lead to zero, which, of course, will cause complete multiplication by zero. I think you’ve already thought about it, since 1000000007 seems to be a prime number, but I mentioned it anyway.
ETA: Recycling Intermediates:
for (@array) { $ans *= $_; print "Before mod: $ans\n"; $ans %= 1000000007; print "After mod : $ans\n"; }
Please note that here you do not need to combine operators.
source share