Massaging Perl Arrays

Is there one line in perl that does 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 indicate the percentage. And he should give me a new array with a given percentage of the original array values.

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

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

Thank.

+5
source share
3 answers

Whenever you want to convert a list mapis a good bet. Here is an example:

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

print "@new";

Conclusion:

50 100 150 200 250
+3
source

map will allow you to convert each item to a list.

my $percent = 50;
my @original = qw/100 200 300 400 500/;
my @manipulated = map { $_ * $percent / 100 } @original;
+7
source

As you asked for one line of perl that does magic, here it is:

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

this gives

50 100 150 200 250
+4
source

All Articles