Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

•Re: Re: Help with number conversion

by merlyn (Sage)
on Apr 03, 2002 at 05:31 UTC ( [id://156240]=note: print w/replies, xml ) Need Help??


in reply to Re: Help with number conversion
in thread Help with number conversion

$number = "0".$number until length $number >= 3;
Did you and Matt Wright go to school together?

{sigh}

-- Randal L. Schwartz, Perl hacker


update: You know, when I first posted my comment, and the post was something Matt-Wright-ish, as I commented above, I left my vote neutral. But when it was changed to:
You know what? merlyn wins. Forget it. I'll stop offering advice before running it past him first.
I finally invoked a downvote. Don't post code here unless you can take open criticism, including a little ribbing and being compared to the bad-code-poster-Child.

Replies are listed 'Best First'.
Re: •Re: Re: Help with number conversion
by tachyon (Chancellor) on Apr 03, 2002 at 09:08 UTC

    This is of course a job for a regex ;-)

    $number = 42; s/.*/"s||000$number|&&join'',reverse chop,chop,chop"/eieio; print;

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

      A regex?

      $number = 42; $number = (' ' x (3 - length $number)) . $number | "000";
      Oh wait, let's not do string bit operations ;)
      $number = 42; $number = ('0' x (3 - length $number)) . $number;
      (The latter is only 50% less efficient than sprintf)

      U28geW91IGNhbiBhbGwgcm90MTMgY
      W5kIHBhY2soKS4gQnV0IGRvIHlvdS
      ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
      geW91IHNlZSBpdD8gIC0tIEp1ZXJk
      

        You can get a substantial improvement over the builtin sprintf with:
        substr "000$num", -3
          
        use strict; use Benchmark qw(cmpthese); my $num = 42; cmpthese (-3, { sprintf => sub { sprintf '%03d', $num }, concat => sub { ('0' x (3 - length $num)).$num }, substr => sub { substr "000$num", -3 }, }); Rate concat sprintf substr concat 244047/s -- -10% -36% sprintf 269956/s 11% -- -29% substr 381628/s 56% 41% --
           MeowChow                                   
                       s aamecha.s a..a\u$&owag.print

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://156240]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-24 15:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found