tags:

views:

71

answers:

1

I have strings similar to 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 a number each of the first values, so it becomes (when 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 have 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;

It fails because of the \($1+$value,. The \( and , is there to as the search eats those.

Any suggestions how to solve it?

+7  A: 

You where almost there, but the part you put in the replacement side of s///e needs to 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 /e evaluates is just a string concatenation:

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

However, when I want to match parts of the string that I don't want to replace, I use lookarounds so those parts aren't part of the replacement:

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";
brian d foy
Wow! lookaround is totally cool! And also the `<<HERE;` trick! Thanks a lot!!!
Sandra Schlichting