-
CGI Question
Hi guys, I'm pretty new to CGI programming. I have a question here, I'm working on a poll script, but could not understand what does this line mean?
foreach my $key (keys %results) {
my $percent = ($results{$key} / $total_votes ) * 100;
$percents{$key} = sprintf("%2d %%", $percent);
}
The main part is that sprintf("%2d %%", $percent), what does sprintf mean? And what are those %2d %%?
Thanks. :wave:
-
Re: CGI Question
No one ever replied :( Could anyone out there helps me please.
Thanks.
-
Re: CGI Question
I have never used CGI before, but Id imagine sprintf ("%2d%%", $percent)
Would display on the screen $percent (the variable) in the format %.%%
% would be the digit before the decimal, 2d would be the decimal, and the 2 %'s after would limit it to decimal places
Sorry I don't know CGI, but I figured it would be better atleast getting some response :)
HTH
-
Re: CGI Question
Ok..I just got here but I'll try to help :)
Regarding the "foreach my $key (keys %results)":
"%results" is a keyed hash array and the code is looping (foreach) through each keyed hash by key name. if you don't specify keys ("(keys %result)") the foreach loop would enumerate by key values instead of key names. The "my $key" is simply specifying what variable you want the enmuerated value to be assigned to.
When using hashes you access values by the key name, thus the "$results{$key}" portion of the next line (the percent sign is used to reference the entire hash while you use the dollar sign when wishing to reference a specific key). The remainder of that line is the apparent math functions.
After what I've covered thus far I imagine that it's obvious to you that with "$percents{$key}" he is assigning a value to another keyed hash and retaining the same key name as is used in the original hash.
sprintf is used to format a string and kfcSmitty is, I believe, correct in his interpetation of that.
Also, if you want or need to investigate other perl functions this page has proven very helpfull to me in the past.
-
Re: CGI Question
kfcSmitty, No, you have been a great help. At least, you gave me an idea of decimals. I was so crazy that could not think of that. %2d means round it to 2 decimals in CGI language, and %% means percent format :)
Also, big thanks to anotherVBnewbie. Man, that site is awesome. I'm glad to know it, so it clarifies the sprintf function clearly.