TurnsCoffeeIntoScripts
TurnsCoffeeIntoScripts

Reputation: 3918

Find a number and incrementing it

I want to create a small perl script that'll find a certain declaration in a c++ header in modify it. So far, I've been able to create the "find" part:

my $buildFile = "..\\Support\\BuildVersion.h";

my @result;
open( File, $buildFile ) or die "Can't open $buildFile.\n";
@result = <File>;
close( File );

print "Updating build version...\n";

open( NEWFOUT, ">", "$buildFile" ) or die "Can't open $buildFile.\n";
foreach( @result )
{
    print $_;
    if( $_ =~ m/#define BUILD_COUNT [0-9]+/ig )
    {
        $_ =~ s/$_/#define BUILD_COUNT 77/;

    }
}
print NEWFOUT @result;
close( NEWFOUT );

So in my c++ file I have this definition named BUILD_COUNT. I want to call this script each time before I build my solution so that it will increment by 1 the value that follows BUILD_COUNT. How could I do that.

Upvotes: 2

Views: 173

Answers (2)

TLP
TLP

Reputation: 67908

A one-liner should be sufficient.

perl -i -pe 's/#define BUILD_COUNT \K(\d+)/$1 + 1/e' yourfile

Using the -i switch without backup is dangerous, but I get the feeling this is what you want. For more safety, but not complete, use -i.bak.

The -p switch will open and read the argument files, the /e option on the substitution operator will cause the replacement expression to be evaluated before it is inserted. The \K escape will cause whatever is before it to be kept.

Upvotes: 10

Himanshu
Himanshu

Reputation: 2454

Capture the version using parentheses into $1 and increment before printing

if( $_ =~ m/#define BUILD_COUNT ([0-9]+)/ig )
{
    my $v = $1 + 1;
    $_ =~ s/$_/#define BUILD_COUNT $v/;

}

Upvotes: 0

Related Questions