Perl FAQ 4.10: Why doesn't Perl interpret my octal data octally?

Perl FAQ 4.10

Why doesn't Perl interpret my octal data octally?

Perl only understands octal and hex numbers as such when they occur as literals in your program. If they are read in from somewhere and assigned, then no automatic conversion takes place. You must explicitly use oct() or hex() if you want this kind of thing to happen. Actually, oct() knows to interpret both hex and octal numbers, while hex only converts hexadecimal ones. For example:

{
    print "What mode would you like? ";
    $mode = <STDIN>;
    $mode = oct($mode);
    unless ($mode) {
	print "You can't really want mode 0!\n";
	redo;
    } 
    chmod $mode, $file;
} 

Without the octal conversion, a requested mode of 755 would turn into 01363, yielding bizarre file permissions of --wxrw--wt.

If you want something that handles decimal, octal, and hex input, you could follow the suggestion in the man page and use:

    $val = oct($val) if $val =~ /^0/;


Other resources at this site: