Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

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

Replies are listed 'Best First'.
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.


        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 (Canon) 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://406653]
Approved by pelagic
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2018-03-18 12:37 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (230 votes). Check out past polls.