in reply to adding 1 to a char of 1

Perl is designed to make string and numeric scalars indistinguishable. It also has a '++' (increment) operator which not only works on numerical strings as well as numbers, but on any string. e.g.
$x = 1; ++$x; # produces 2 or "2" (transparent which) $x = "1"; ++$x; # the same $x = "A"; ++$x; # produces B
To strip leading zeros:
$char =~ s/^(0)+//;
see the perlop documentation for more details.

-M

Free your mind

Replies are listed 'Best First'.
Re^2: adding 1 to a char of 1
by Anonymous Monk on Jun 20, 2006 at 17:38 UTC
    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);
      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...

      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)++;