Re: Variable division, assignment and sprintf in one line



From: Steve Bertrand <iaccounts@xxxxxxxxxx>
Hi again all,

Is there a way that one can use sprintf on a variable and assign the
value back to the variable without having the leading $var= ?

$var = sprintf ("%.2f", (($var /=1024) /=1024)))

What the ...?!?

/= ?

You divide the value of $var by 1024, assign it back to $var, divide
it by another 1024, assign it again to $var, then format the
resulting number using sprinf() and assign it to $var?!? Why???

$var = sprintf ("%.2f", (($var / 1024) / 1024));

will do the same as will

$var = sprintf ("%.2f", $var / (1024*1024));

And it will be more efficient because the multiplication will be done
at compile time (once) and you'll only do a single division each
time. Which is also more precise, though in this case it doesn't seem
to matter.

Jenda
===== Jenda@xxxxxxxxxxx === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery

.



Relevant Pages

  • Re: a declaring
    ... I should add that variable declaration happens at compile time, while assigning happens at run time. ... my $var = 123; ...
    (perl.beginners)
  • Re: regular expr.
    ... You dont require regex for that use printf or sprintf ... print $var; ... HTH ...
    (perl.beginners)
  • RE: fixed width variable
    ... perldoc -f sprintf ... I have been searching for a way to do this and have not had any luck. ... $var would be 5. ...
    (perl.beginners)
  • Variable division, assignment and sprintf in one line
    ... Is there a way that one can use sprintf on a variable and assign the ... value back to the variable without having the leading $var=? ... I've got a hash of hashrefs of hashrefs and I'd rather not specify the ...
    (perl.beginners)