asiufy has asked for the wisdom of the Perl Monks concerning the following question:

Hello all,
When I run this...
use CGI; $query = new CGI; print $query->header; $a = sprintf("%04b", 10); print $a;
... I get "%04b" on the web browser, and "1010" from the command line, which is what I expect (binary conversion of the decimal "10").
Does anybody know why sprintf() is not working as expected when used thru CGI?
Thanks.

Replies are listed 'Best First'.
(jeffa) Re: sprintf() and CGI
by jeffa (Bishop) on May 10, 2001 at 02:23 UTC
    Invalid conversion in sprintf: "%b" at ./foo.cgi line 13.
    Use -w and strict, then you will see that it's %d, not %b
    major apologies :#

    UPDATE:

    sorry, i see what you are wanting to do now, you should use pack and unpack instead of sprintf:

    my $a = unpack("B32", pack("N", $a)); $a =~ s/^0+(?=\d)//; print $a;
    I did a SuperSearch on 'convert binary decimal' and came across How do I convert between decimal and binary?.

    jeff "will move to 5.6 someday real soon" a

      Jeff, thanks for the valid points ("strict" and "-w"), but that was just a quick example I wrote to exemplify the problem I found on a bigger script (which uses both "strict" and "-w").

      The problem is that I don't want a decimal but a binary back, that's why I used "%b", as described here.

      In fact, I ran your script, replacing the "d" for a "b", and it worked just fine on the command line (just like mine did before, even though it didn't had -w and strict on). But when I run it through the browser (as a CGI), it still returns "%04b"...

      btw this is Perl 5.6.1 on Solaris 2.8 with Apache 1.3.19.
      Well, but I still find it strange that sprintf("%b") works right from the command line, but fails from CGI...

      I understand the "%b" is a recent (5.6.0) feature, so maybe no one noticed yet this behavior...

        Sounds like your CGIs are using a different version of Perl than you get from your command-line. Change your script to also print out $] (and perhaps "@INC") to see.

                - tye (but my friends call me "Tye")