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

Hello, I'm trying to create a package of contants that I can import into other packages and scripts. In particular, I want to define octal constants for use with the PERL function chmod. Here's my code
package Constants; use base Exporter; @ISA = qw (Exporter); @EXPORT = qw( $var1 $var2); $var1 = \'val1'; $var2 = \'val2';
This works but I'd wanted to add some octal constants so I added the following code to the above:
use constant B_OGUS => 0620;
I included B_OGUS in @EXPORT which returned in proper value in decimal (400) but not in octal. How can I get the value to return in octal so I can use it in chmod? chmod(B_OGUS,$filename); Thank you

Replies are listed 'Best First'.
Re: constant issue
by ferreira (Chaplain) on Jan 19, 2007 at 16:38 UTC

    chmod's first argument is a number, which most of the time is written in source code as an octal number (like 0620). But this is a convenience for the reader of the code, since octal numbers are much easy to interpret as Unix permission modes (which are split in groups of 3 bits).

    However, for Perl, this

    chmod 400, @files
    works the same as
    chmod 0620, @files

    So I recommend you use your constants just like you did and when you want to take a look at its value use

    sprintf "0%o", B_OGUS # returns "0620"

    Also be sure to read the note in chmod documentation about this argument as a number and not as a string to avoid another common mistake.

Re: constant issue
by Joost (Canon) on Jan 19, 2007 at 16:38 UTC
    You should be able to use decimal 400 as the value, since octal / hexadecimal / decimal literal representations of the same value ARE the same value. 0620 == 400 == 0x190

    Note that you can only use octal and hexadecimal notation in numeric literals. String literals Strings used as numbers are always interpreted as decimal (and you should use oct() and hex() to convert octal and hexadecimal strings to numbers.

    update: note also that numbers converted to string (as in print $number) also always result in decimal notation unless you use special formatting (like printf())

Re: constant issue
by ikegami (Patriarch) on Jan 19, 2007 at 16:46 UTC

    400, 0620 and 400.0, 4*100 are all the same number. Perl doesn't recognize any difference. They can be used interchangeably.

    If you use a representation that Perl doesn't recognize, that's when trouble starts. For example, Perl doesn't recognize '0620' as a representation of 400. That means '0620' is not the same number as 0620. (But oct('0620') is.)

Re: constant issue
by moklevat (Priest) on Jan 19, 2007 at 16:51 UTC
    In addition to the advice provided by the monks above, you may want to consider whether using Readonly might be preferable than using constant in this case. There was a good discussion of this in a thread called Using Constants in Perl.