Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I multiply each member of array by a scalar in perl?

Here is the code...

use strict;
use warnings;

my @array= (1,2,3,4,5);
my $scalar= 5;

@array= $scalar*@array;

print @array;

Need something that can perform similar function with little code. Thanks!

like image 841
masterial Avatar asked Apr 15 '11 00:04

masterial


2 Answers

it seem unfortunate to me that Larry didn't allow

$scalar operator (list)

or

(list) operator $scalar

Sure map or loops can do it, but the syntax is so much cleaner like above.

Also (list) operator (list)

makes sense too if the 2 are equal length.

Surprised Larry didn't allow these, just saying.. I guess in this case there were (n-1) ways to do it.

Like

my @a = 'n' . (1..5); my @a = 2 * (1..5);

or even my @a = 2 * @b;

like image 121
Milton Earnest Zilmer Avatar answered Jan 01 '23 20:01

Milton Earnest Zilmer


You can try this:

@array = map { $_ * $scalar } @array;

or more simply:

map { $_ *= $scalar } @array;
like image 33
Ted Hopp Avatar answered Jan 01 '23 20:01

Ted Hopp