I want to update a release number in a C file where it is present in the form of a macro. I want to implement this in perl. I have done a small implementation but I'm eager to understand if this is the right solution or it can be optimsed further.
The C file (input file: test_file.c) is as given below:
INPUT_FILE (test_file.c)
#include "header_file.h"
#define ALPHA_MAJOR_VERSION 100
#define ALPHA_MINOR_VERSION 20
#define BETA_MAJOR_VERSION 1
#define BETA_MINOR_VERSION 2
#define DELTA_BRANCH_VERSION 3
#if ((ALPHA_MAJOR_VERSION != SOME_VERSION) || \
(ALPHA_MINOR_VERSION != SOME_OTHER_VERSION))
#error Versions do not match
typedef int fix_this_compiler_error;
#else
typedef int fix_this_compiler_error;
#endif
Lets say that the release number is 101p1p2p3p4, I want to split this release number and update the macros in the C file as shown below:
#define ALPHA_MAJOR_VERSION 101
#define ALPHA_MINOR_VERSION 1
#define BETA_MAJOR_VERSION 2
#define BETA_MINOR_VERSION 3
#define DELTA_BRANCH_VERSION 4
Here in the release number 101p1p2p3p4 the value after every p is a major/minor version for the release and same needs to be updated in the C file. So the desired output look something like this:
DESIRED_OUTPUT
#include "header_file.h"
#define ALPHA_MAJOR_VERSION 101
#define ALPHA_MINOR_VERSION 1
#define BETA_MAJOR_VERSION 2
#define BETA_MINOR_VERSION 3
#define DELTA_BRANCH_VERSION 4
#if ((ALPHA_MAJOR_VERSION != SOME_VERSION) || \
(ALPHA_MINOR_VERSION != SOME_OTHER_VERSION))
#error Versions do not match
typedef int fix_this_compiler_error;
#else
typedef int fix_this_compiler_error;
#endif
MY_IMPLEMENTATION
#!/usr/bin/perl
use strict;
use warnings;
my $release_num = "101p1p2p3p4";
my @array = split(/p/, $release_num);
my @versions;
for (my $i=0; $i<scalar(@array); $i++)
{
$versions[$i] = $array[$i];
}
print "array is : @versions \n";
print "0 : $versions[0] \n";
print "1 : $versions[1] \n";
print "2 : $versions[2] \n";
print "3 : $versions[3] \n";
print "4 : $versions[4] \n";
my $file = '/path/to/the/file/test_file.c';
`sed -i '/^\#define ALPHA_MAJOR_VERSION/ c\\#define ALPHA_MAJOR_VERSION $versions[0]' $file`;
`sed -i '/^\#define ALPHA_MINOR_VERSION/ c\\#define ALPHA_MINOR_VERSION $versions[1]' $file`;
`sed -i '/^\#define BETA_MAJOR_VERSION/ c\\#define BETA_MAJOR_VERSION $versions[2]' $file`;
`sed -i '/^\#define BETA_MINOR_VERSION/ c\\#define BETA_MINOR_VERSION $versions[3]' $file`;
`sed -i '/^\#define DELTA_BRANCH_VERSION/ c\\#define DELTA_BRANCH_VERSION $versions[4]' $file`;
With my implementation I'm able to get the desired output as shown above , but want to understand that this is the right way to solve this problem or there can be a better method.
I asked similar question before but it was closed by moderators as i didn't share my work. I hope this question will not be closed because I've put an effort to propose a solution. Thanks!
Link to closed question: How can i update a macro in a C file using perl