FAQ 4.3 Why isn"t my octal data interpreted correctly?

FAQ 4.3 Why isn"t my octal data interpreted correctly?

am 29.09.2007 15:03:04 von PerlFAQ Server

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

------------------------------------------------------------ --------

4.3: Why isn't my octal data interpreted correctly?

Perl only understands octal and hex numbers as such when they occur as
literals in your program. Octal literals in perl must start with a
leading 0 and hexadecimal literals must start with a leading "0x". If
they are read in from somewhere and assigned, no automatic conversion
takes place. You must explicitly use "oct()" or "hex()" if you want the
values converted to decimal. "oct()" interprets hexadecimal (0x350),
octal (0350 or even without the leading 0, like 377) and binary
("0b1010") numbers, while "hex()" only converts hexadecimal ones, with
or without a leading "0x", such as 0x255, "3A", "ff", or "deadbeef". The
inverse mapping from decimal to octal can be done with either the <%o>
or %O "sprintf()" formats.

This problem shows up most often when people try using "chmod()",
"mkdir()", "umask()", or "sysopen()", which by widespread tradition
typically take permissions in octal.

chmod(644, $file); # WRONG
chmod(0644, $file); # right

Note the mistake in the first line was specifying the decimal literal
644, rather than the intended octal literal 0644. The problem can be
seen with:

printf("%#o",644); # prints 01204

Surely you had not intended "chmod(01204, $file);" - did you? If you
want to use numeric literals as arguments to chmod() et al. then please
try to express them as octal constants, that is with a leading zero and
with the following digits restricted to the set 0..7.



------------------------------------------------------------ --------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.