Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Help with Numbers..Please

by perlguy (Deacon)
on Apr 24, 2003 at 14:45 UTC ( [id://252911]=note: print w/replies, xml ) Need Help??


in reply to Help with Numbers..Please

Update: Abigail-II's point is well taken on posting incorrect code. Strike this one and don't bother. I found the problem case after I had already posted. Appologies.

Update 2: This following regex should work better, and won't fail in the test cases. The same number of digits will be in the output, unless all 9s are in the string, in which case it will just add 1 digit to the front of the string to accomodate. Again, just an exercise.

$number =~ s/([^9]?9*)$/$1+1/e;

Back to the original post:

Here is a regular expression way to do it:

my $number = '0001999'; $number =~ s/([^9]9+|\d)$/$1+1/e; print "$number\n";

It has a flaw: if all the numbers are 9, it will drop the last nine and add a 10, so probably not something you would want to use in production code. But the other test cases that I worked with were fine. It was more of an exercise than anything.

Replies are listed 'Best First'.
Re: Help with Numbers..Please
by Abigail-II (Bishop) on Apr 24, 2003 at 14:54 UTC
    Uhm, if you already know it's flawed, by bother posting? How useful is incorrect code?

    Anyway, here's a regexp solution that is much simpler, and doesn't fail on "9":

    s/(\d+)/$1+1/e;

    Abigail

      It won't fail on '9', but your proposed alternative regular expression won't work on '009' for example, as '10' would be the output instead of the requested '010'. Just an observation.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2025-07-18 01:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.