Previous Page
Next Page

4.6. Leading Zeros

Don't pad decimal numbers with leading zeros.

Several of the guidelines in this book recommend laying out data in table format, and aligning that data vertically. For example:


    use Readonly;

    Readonly my %ATOMIC_NUMBER => (
        NITROGEN   =>    7,
        NIOBIUM    =>   41,
        NEODYNIUM  =>   60,
        NOBELIUM   =>  102,
    );

But sometimes the desire to make columns line up cleanly can be counterproductive. For example, you might be tempted to pad the atomic weight values with zeros to make them uniform:

    use Readonly;

    Readonly my %ATOMIC_NUMBER => (
        NITROGEN   =>  007,
        NIOBIUM    =>  041,
        NEODYNIUM  =>  060,
        NOBELIUM   =>  102,
    );

Unfortunately, that also makes them wrong. Even though leading zeros aren't significant in mathematics, they are significant in Perl. Any integer that begins with a zero is interpreted as an octal number, not a decimal. So the example zero-padded version is actually equivalent to:

    use Readonly;

    Readonly my %ATOMIC_NUMBER => (
        NITROGEN   =>   7,
        NIOBIUM    =>  33,
        NEODYNIUM  =>  48,
        NOBELIUM   => 102,
    );

To avoid this covert transmutation of the numbers, never start a literal integer with zero. Even if you do intend to specify octal numbers, don't use a leading zero, as that may still mislead inattentive future readers of your code.

If you need to specify octal values, use the built-in oct function, like so:


    use Readonly;

    Readonly my %PERMISSIONS_FOR => (
        USER_ONLY     => oct(600),
        NORMAL_ACCESS => oct(644),
        ALL_ACCESS    => oct(666),
    );

    Previous Page
    Next Page