There are several ways.

Here's an explicit way using length and treating the 'number' like a string:

use strict; use warnings; my $number = 123; my $pad = 9 - length $number; $number = '0' x $pad . $number; print "$number\n";

The sprintf approach is tidier:

use strict; use warnings; my $number = 123; $number = sprintf "%09u", $number; print "$number\n";

Update: When only a RE will do, here's a regex approach with the s/// operator. It's not as clean as the sprintf approach, but you may have your reasons for using it:

$number = 123; $number =~ s/(\d{0,9})$/'0' x (9 - length $1) . $1/e; print "$number\n";

Update 2: It's been said that it can't be done with a m// regex, and I suppose for a pure regular expression implementation that's true. But I couldn't just leave it at that, so here's a m// regex approach that works by taking liberties with what is being bound to the m// operator:

my $number = 123; print "$number\n" if ($number) = ( '0' x 9 . $number ) =~ m/(\d{9})$/;


Dave


In reply to Re: adding characters via a regular expression by davido
in thread adding characters via a regular expression by jwking

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.