in reply to Re: Odd behavior of $#
in thread Odd behavior of $#

$# applies only to print itself doing the conversion. Interpolating the variable into a string doesn't bring it into play.
Exactly! Which is why this line works:
print "\n","  $amount   ","-", $taxes," = ", $amount-$taxes;

Also note that $# is deprecated...
Which JamesNC would have known if he had enabled warnings.

... and it's better to explicitly run through sprintf than depend on it.
Is there a way to tell sprintf to add a dollar sign? Or do you have to explicitly append it? Like:
my $net = '$'.sprintf("%.2f", $amount - $taxes);

Replies are listed 'Best First'.
Re (3): Odd behavior of $#
by VSarkiss (Monsignor) on Feb 19, 2003 at 19:52 UTC

    Is there a way to tell sprintf to add a dollar sign?
    Sure, just: my $net = sprintf '$ %.2f', $amount - $taxes;You can put whatever you like in the format string.

    For more complicated things, you can try Number::Format. It's a little heavyweight for my taste, but it works.

Re^3: Odd behavior of $#
by diotalevi (Canon) on Feb 19, 2003 at 19:52 UTC
      The difference I am seeing is that you have double quotes and no space, the previous post had single quotes and a space. The single quotes make it so that you don't need the \ in front of the $ (unless I am once again mistaken ;) ).
Re: Re: Re: Odd behavior of $#
by Fletch (Bishop) on Feb 19, 2003 at 20:36 UTC

    Right, that case works because print itself is doing the conversion. If $# is set then each element passed to print is looked at to see if it can be converted to an IV or an NV. If it can, it's formatted using $#. Spaces don't matter when considering if it's numeric, so "  1.23456  " doesn't look any different than a numeric 1.23456 (and in fact the spaces will be stripped before the conversion is done).

    $ perl -le '$#="%0.2f";$a=1.2345;print "|", " $a ", "|";' |1.23|

    However in the other cases, there's more than spaces and digits (and decimals, and whatnot that perl recognizes as a numeric) so it's not seen as an IV or NV and not treated to the $# munging. See Perl_do_print in doio.c for the complete skinny on what exactly happens.