Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

use of print f and sprint f

by replicant4 (Novice)
on Nov 10, 2004 at 12:08 UTC ( #406653=perlquestion: print w/ replies, xml ) Need Help??
replicant4 has asked for the wisdom of the Perl Monks concerning the following question:

mighty perl monks. I have the following print line.
printf "$l,$j,$Hx,$Hy,$Hxy,$mutual\n";
How can I use printf or sprintf in order to get only 3 decimal places for each of my $Hx, $Hy, $Hxy and $mutual values? Thanks in advance for your help

Comment on use of print f and sprint f
Download Code
Re: use of print f and sprint f
by busunsl (Vicar) on Nov 10, 2004 at 12:16 UTC
    Have a look at the dokumentation of printf:

    perldoc -f sprintf

    You need a format string to format your values. You can try something like this:

    printf "$l, $j, %.3f, %.3f, %.3f, %.3f\n", $Hx, $Hy, $Hxy, $mutual;

      You should probably get into the habit of avoiding the interpolation of unchecked variables directly into the format string of (s)printf (as with $l and $j here) as a general rule - there has been some concern over the last few years about Format String vulnerabilities, and whilst it is not a flaw in Perl itself the underlying C libraries could potentially be vulnerable.

      /J\

        Hm, does this vulnerability really exist in perl? perldoc -f sprintf says perl uses its own formatting (just emulating libc's sprintf). The only exception are floating point numbers (with standard modifiers). I am not a security expert, but maybe someone who is (or someone who has digested the whole linked article) can tell if perl is really vulnerable here.
Re: use of print f and sprint f
by Happy-the-monk (Abbot) on Nov 10, 2004 at 12:21 UTC

    ...printf or sprintf in order to get only 3 decimal places...

    According to perldoc -f sprintf, do it this way:

    printf "$l,$j,%.3f,%.3f,%.3f,%.3f\n", $Hx, $Hy, $Hxy, $mutual;

    Cheers, Sören

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2015-07-07 02:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (86 votes), past polls