Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Can i do math with the elements of an array?

by girl (Initiate)
on Oct 20, 2011 at 13:39 UTC ( #932661=perlquestion: print w/replies, xml ) Need Help??

girl has asked for the wisdom of the Perl Monks concerning the following question:

The title is a joke, my real question is:Is it possible to do math operations on the elements of an array? Like to add, subtract and print the answer with them?
  • Comment on Can i do math with the elements of an array?

Replies are listed 'Best First'.
Re: Can i do math with the elements of an array?
by zentara (Archbishop) on Oct 20, 2011 at 14:33 UTC
    You can loop thru your array or map the array, and perform whatever math you want on each element. But if you are talking about math operations on the ENTIRE array, you are looking at vector math. See PDL, it's piddles are arrays which can have math done on the entire array in one step. See PDL homepage and The PDL Newbook tutorial

    But here is a simple map usage:

    #!/usr/bin/perl use strict; use warnings; my @array = ( 1..10 ); print "@array\n"; my @mult = map { $_ * 2 } @array; print "@mult\n";

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh
Re: Can i do math with the elements of an array?
by Util (Priest) on Oct 20, 2011 at 14:26 UTC
    Yes.
    my @z = ( 30, 18, 54, 24, 88 ); my $sum = $z[1] + $z[3]; print $sum, "\n"; # Prints "42"
Re: Perl dosen't tell me how magnets work! :(
by clueless newbie (Deacon) on Oct 20, 2011 at 13:52 UTC
    Surely it does ...
    perl -MLWP::Simple -e "print get('http://www.howmagnetswork.com/')"
Re: Can i do math with the elements of an array?
by aartist (Pilgrim) on Oct 20, 2011 at 14:15 UTC
    Yes. What did you try so far?
Re: Can i do math with the elements of an array?
by JavaFan (Canon) on Oct 20, 2011 at 18:25 UTC
    Yes.

    I wonder, did you encounter something that makes you think this would not be the case?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://932661]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2020-07-16 15:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?