views:

76

answers:

3

Is there a single line in perl which does some magic like this.

Array = [100,200,300,400,500];

percent = 50%

new_Array = [50,100,150,200,250];

That is, I give an array and specify a percent. And it should give me a new array with the given percent of original array values.

should take care of odd numbers and give me either ceiling or floor of that value.

I know how to do it manually. Just wondering if perl has something surprising in store?

Thank you.

+6  A: 

map will allow you to transform every item in a list.

my $percent = 50;
my @original = qw/100 200 300 400 500/;
my @manipulated = map { $_ * $percent / 100 } @original;
David Dorward
You might need to throw in a explicit `int()` in the map since it sounds like the questioner wants rounding.
Hudson
Thanks. that's indeed a great solution :)
jerrygo
+2  A: 

Whenever you want to transform a list, map is a good bet. Here's an example:

my @list = ( 100, 200, 300, 400, 500 );
my @new  = map { int( $_ * 0.5 ) } @list;

print "@new";

Output:

50 100 150 200 250
friedo
thanks :) that does the rounding stuff.
jerrygo
+3  A: 

As you asked for a single line of perl that does the magic, here it is:

print join " ", map { int( $_ * 0.5) } (qw(100 200 300 400 500));

this gives

50 100 150 200 250
dalton
Thank you. That works too :)
jerrygo