0

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.

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, just what I was looking for
3

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

1 Comment

@choroba,the outstanding "bugs" tend to follow a couple patterns. The biggest one is "Wishlist"--it's somebody's idea of something they would like MoreUtils to do, but it doesn't. The next group are things that are not officially marked as fix, but if you take a look at the thread, a fix was put in. And then, there are issues like if you pass the XS version a "bad array reference", you get a segfault. So, the trick is not to pass it a bad array reference. I worked at a Perl shop where a lot of guys used this mod pretty heavily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.