Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Getting the ascii number through perl's printf

by virtualsue (Vicar)
on Jan 10, 2007 at 04:45 UTC ( #593823=note: print w/replies, xml ) Need Help??


in reply to Getting the ascii number through perl's printf

As jettero says, you must use ord if you want Perl to output an ASCII value. The C idiom you are using doesn't make sense in Perl.

#!/usr/bin/perl use warnings; use strict; print ord('c'), "\n";
The 'c' in your C snippet looks just like the 'c' in your Perl snippet, but they're not the same. In C, as you already know, 'c' is a char, a character constant which can be readily exchanged for its corresponding ASCII value. In Perl, 'c' is a scalar value that is also referred to as a string literal. There is no such thing as a char in Perl, though a string literal can certainly contain only one character. I encourage you to read (and refer back to) perldata. With that out of the way, why did your program spit out a warning and convert your string literal 'c' to 0? Grandfather said that it was because Perl "numified" 'c', and that this is Perl slang which means 'what happens when a scalar is used in is a numeric context'. The following snippet may shed a bit more light, try running it.
#!/usr/bin/perl use warnings; use strict; printf "%d\n", '1234'; # The entire string is an integer printf "%d\n", '12c3'; # printf stops the format conversion at the fi +rst non-integer printf "%d\n", 'c123'; # No characters converted, 0 is returned printf "%d\n", '0c123'; # Conversion stops after first character, 0 is + returned

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://593823]
help
Chatterbox?
[jdporter]: one prog I have has a UI which allows to input a bit mask
[jdporter]: currently it expects the bitmask to be in the form of a hex number, e.g. 0x0101
[jdporter]: but I'd like to let the user specify it as individual bits, i.e. 0b0000000100000001
[jdporter]: there is no bit/binary equivalent of hex, right?
[jdporter]: I guess that the most direct way of doing it is with some magical incantation involving unpack or whatever
[jdporter]: let me google that for me ;-)
[jdporter]: hex points explicitly to oct, which does the job. :-D

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2018-02-20 16:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When it is dark outside I am happiest to see ...














    Results (272 votes). Check out past polls.

    Notices?