How can I find and increment a number in a larger Perl string?

I have lines like this

INSERT INTO `log_action` VALUES (1,'a',1,4),(2,'a',1,1),(3,'a',4,4),(4,'a',1,1),(5,'a',6,4);

where I would like to add the number of each of the first values, so it becomes (when the value is 10)

INSERT INTO `log_action` VALUES (11,'a',1,4),(12,'a',1,1),(13,'a',4,4),(14,'a',1,1),(15,'a',6,4);

I tried this

#!/usr/bin/perl -w
use strict;
my $input;
if ($#ARGV == 0) {
    $input = $ARGV[0];
} else {
    print "Usage: test.pl filename\n\n";
    die "Wrong number of arguments.\n";
}
my $value;
$value = 10;
open(FILE, '<', $input) or die $!;
foreach my $line (<FILE>) {
    if ($line =~ m/^INSERT INTO \`log_action\` VALUES/) {
    $line =~ s/\((\d+),/\($1+$value,/ge;
    print $line . "\n";
    }
}
close FILE;

He fails because of \($1+$value,. \(and ,are where the search eats them.

Any suggestions for resolving it?

+3
source share
1 answer

You where almost there, but the part that you put on the replacement side s///emust be valid Perl. You are evaluating Perl code:

my $string =<<HERE;
INSERT INTO `log_action` VALUES 
(1,'a',1,4),(2,'a',1,1),(3,'a',4,4),(4,'a',1,1),(5,'a',6,4);
HERE

my $value = 10;
$string =~ s/\((\d+),/ '(' . ($1+$value) . ',' /ge;
print "$string\n";

The Perl code that is evaluated /eis simply a string concatenation:

 '(' . ($1+$value) . ','

, , , lookarounds, " t :

my $string =<<HERE;
INSERT INTO `log_action` VALUES 
(1,'a',1,4),(2,'a',1,1),(3,'a',4,4),(4,'a',1,1),(5,'a',6,4);
HERE

my $value = 10;
$string =~ s/ (?<=\() (\d+) (?=,) / $1+$value /xge;
print "$string\n";
+9

Source: https://habr.com/ru/post/1760525/


All Articles