in reply to Re: adding 1 to a char of 1
in thread adding 1 to a char of 1

Thanks everyone for your help, it works fine now.... One last question.... now that I have the correct number, how do I only grab the last 4 digits so for example:
my original number was 9 but now with the code u guys gave me, we incr +emented into 10. I need to plug this number back into the file name b +ut creating a new file called "name_0010" (originally it was "name_00 +09"). Here is the code I currently have, I know theres a more efficie +nt way to do this... $newfile = substr($newfile_n,0, 4); $newfile =~ s/^(0)+//; ++$newfile; print"$newfile\n"; $newfile = "000".$newfile; #if it gets to 100 then it will look like t +his "0100" substr($newfile, 1, 4);

Replies are listed 'Best First'.
Re^3: adding 1 to a char of 1
by liverpole (Monsignor) on Jun 20, 2006 at 18:14 UTC
    Not sure why you're using substr.  Let me suggest that you keep the index and the basename separate.

    For example:

    my $index = 0; for (my $i = 0; $i < 100; $i++) { $index++; my $fullname = sprintf "base_%04d", $index; printf "fullname = '%s'\n", $fullname; }

    will print 100 different names, starting with "name_0001" and ending with "name_0100".  The %04d achieves this result; the "0" left-pads the integer value with zeroes, and the "4" gives you 4 decimal places.

    Read up on sprintf to get more details:  perldoc -f sprintf.

    If you absolutely must get the last 4 digits of a string, you can use "substr" like this:

    $last_4_chars = substr($my_string, -4);

    This has the effect of taking the "rest" of the string, starting at the 4th character from the end (since the offset -4 is negative) rather than from the beginning.


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
      Great thats exactly what I was looking for.... Thanks to all u wisemen and women...
Re^3: adding 1 to a char of 1
by ikegami (Patriarch) on Jun 20, 2006 at 20:47 UTC

    Use substr to extract and replace:

    my $oldfile = "name_0009"; my $num = substr($oldfile, -4); ++$num; my $newfile = substr($oldfile, 0, -4) . $num;

    Or use the lvalue form to simplify things:

    my $oldfile = 'name_0009'; substr(my $newfile = $oldfile, -4)++;