
japhy
Enthusiast
Dec 31, 2000, 2:00 PM
Post #4 of 4
(639 views)
|
|
Re: Adding up a column in array
[In reply to]
|
Can't Post
|
|
You're asking questions about what functions are doing (split() and printf()). These can probably be answered by taking a look at the perlfunc documentation in one of the following ways: 1. typing perldoc -f split and perldoc -f printf at your command prompt 2. referring to the chapter in "Programming Perl" that lists the built-in functions and their uses (the same as the perlfunc docs, really) 3. reading the content online at http://www.perldoc.org/ If you're not familiar with perldoc, get familiar. It saves everyone a lot of time, and it will make you a smarter, better, and more learned Perl programmer. I will, though, explain my code. I create this variable with my() because I am assuming the program is being run under the use strict pragma (which you should be using). It makes a local variable (a variable that is not global), which disappears from existence after the block it is in closes (so long as nothing is relying on its existence, like a reference).
for (@array) { $sum += (split)[2] } This iterates over the values in an array, called @array. Each element can be accessed by the "pronoun" variable $_. I then call split(), which, given no arguments, assumes it's being called as split(' ', $_), which will return a list of non-whitespace chunks of text. I wrap the call in parentheses to treat the return value like a list, and then use the [2] subscript on it to get the third element in the list (the first element has an index of 0, so the third element has an index of 2).
printf "sum = %.1f\n", $sum; The printf() function (borrowed from C) takes a formatting string and a list of values to format per the string. The %f format means "insert a floating point number here", and the .1 information in it means "1 digit after the decimal point". This is needed to make the number 6 appear as 6.0. If you do not want to print the value, but rather store the formatted value, use the sprintf() function instead:
$formatted_sum = sprintf "%.1f", $sum; I hope this clears things up for you. Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author
|