Incrementing an integer at the end of a string in perl
Asked Answered
V

3

6

I have a string in the following format:

\main\stream\foo.h\3

it may have more or less "sections", but will always end with a slash followed by an integer. Other examples include:

\main\stream2309\stream222\foo.c\45

\main\foo.c\9

I need to, in Perl, increment the number at the end of the string and leave the rest alone. I found an example on this site that does exactly what I want to do (see Increment a number in a string in with regex) only the language is Javascript. The solution given was:

.replace(/\d+$/,function(n) { return ++n })

I need to do the same thing in Perl.

Viniculture answered 19/7, 2010 at 19:45 Comment(0)
L
11

You can use the /e regex modifier to put executable code in your replacement string.

Something like:

$string =~ s/(\d+)$/$1 + 1/e;

should work.

Legpull answered 19/7, 2010 at 19:49 Comment(1)
Too bad auto-increment is limited to strings that match /^[a-zA-Z]*[0-9]*\z/Deaminate
S
2

Try $var =~ s/(\d+$)/($1 + 1)/e

Schoolteacher answered 19/7, 2010 at 19:50 Comment(0)
B
0

If you want an underscored suffix and the original string might not have a suffix:

value
value_1
value_2
...

you can use this:

$foo =~ s{_?(\d*)$}{'_'.($1 eq '' ? 1 : $1+1)}e
Beyond answered 16/3, 2023 at 16:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.