Again, why a regex?
use strict; print pad($_,5), "\n" for (qw(3.14 1 10 100 1000)); sub pad { my ($str,$pad) = @_; my ($add,$right); ($str,$right) = split('\.',$str,2); $right = ($right) ? ".$right" : ''; $add = $pad - length($str); return $str . $right if $add < 1; return ('0' x $add) . $str . $right; }
Sorry, but after reading this i was curious to find a non-regex way. TIMTOWTDI :)

UPDATE: Woah! I made a HUGE mistake! Thanks to Albannach for pointing it out. Code has been modified:

old: return $str if $add < 1; new: return $str . $right if $add < 1;
That was dumb. As a matter of fact, trying to get my code to right zero pad decimals (3.1400), instead of left padding (003.14) as it currently does - and for the record, that is NOT A BUG! it is a feature! - well, that's just dumb. i am going to stick with sprintf. :)

and don't chastise me about scientific notation, davorg! ;)

(for the record - for 'some reason' i was thinking the problem was to merely zero pad numbers - oi vey!)

jeffa

just say no to testing your new installation of cygwin on Win32 by trying to simulate a small subset of sprintf in Perl and posting it on PerlMonks


In reply to (jeffa) Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge by jeffa
in thread Using Regular Expressions to Simulate sprintf() function - One Liner Challenge by Incognito

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.