I have an array of values which I'd like to transform using another array, like so
@raw_values = qw(10 20 30 40);
@adjustment_factors = qw(1 2 3 4);
#the expected value array
@expected_values = qw(10 40 90 160);
Is there a more perlish way to doing that then this?
for my $n (0..$#raw_values){
$expected_values[ $n ] = $raw_values[ $n ] * $adjustment_factors[ $n ]
}
The arrays always have the same number of elements, and I have a few thousand to process.
Use map
:
@expected_values = map { $raw_values[$_] * $adjustment_factors[$_] } 0 .. $#raw_values;
Another option is to first assign the original values and then modify them:
@expected_values = @raw_values;
$x = 0;
$_ *= $adjustment_factors[$x++] for @expected_values;
Or, if you do not need @adjustment_factors
anymore, you can empty it:
@expected_values = map { $_ * shift @adjustment_factors } @raw_values;
pairwise
is the more idiomatic, CPAN solution.
use List::MoreUtils qw<pairwise>;
my @expected_values = pairwise { $a * $b } @raw_values, @adjustment_factors;
See List::MoreUtils
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.