Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

multiplying array by constant

Status
Not open for further replies.

horlage

Programmer
Joined
Jul 3, 2007
Messages
2
Location
US
How do I multiply an array by a constant in Perl? I didn't turn up anything with a cursory Google search.

Here's what I want (pseudo-code):

@array = (1, 4);
print 3 * @array;

output:
(3, 12)


Thanks a lot.
 
There's no way other than multiplying individually each element by the constant.
You can write it more or less graciously, you can write a routine that does it changing the content of the array, there is also a Matrix module (but personally wouldn't even look at it for such a simple task), but that's it: no matrix manipulation instructions available with perl (as with almost all languages).

prex1
: Online tools for structural design
: Magnetic brakes for fun rides
: Air bearing pads
 
Code:
$_ *= 3 for @array;
 
no matrix manipulation instructions available with perl (as with almost all languages).

It depends on what you are defining as a matrix. If you mean something like an array of arrays, or a multi-dimensional array, there is plenty of perl documentation for that.


In addition to Ishids example, that changes the array elements, here is a way that does not:

Code:
@array = (1,4);
print map {$_ * 3,"\n"} @array;

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top