开发者

Can I use search and replace to insert a progressive number in Perl?

I am sorry, if this question sounds stupid, but I have searched a lot and by now I am working the better part of a day on a rather trivial task.

I need to insert progressively numbered IDs into a text file. There are already Placeholders in the file, so that I would tend to work with search and replace. The best I could do was the following:

#!/usr/bin/perl
my $counter = 1;
my $oldID = "docID=\"";
my $newID = "docID=\"14$counter"; #should the return the IDs 141, 142, 143 ...

open (FILE, "file.txt") || die $!;
@content = <FILE>;

foreach (@content){
s/$oldID/$newID/;
$counter++;
}

open (OUT, ">file_ID.txt") || die $!;
print OUT @content;
close OUT;
close(FILE);

print = "$counter" #this is to test if the counter is working.

this finds and replaces the docID="". Unfortunaately it replaces all of the occurences of docID with 141.

I would suppose that it doesn't work because all the occurences get replaced all at once and the counter never gets a chance to grow larger. This however does not look plausible if I see $counter growing way too large. It is exactly 12 times the number of occurences of docID.

I believe I need to get perl to replace only one occurence of docID, then raise the counter and then do this in a loop 开发者_开发百科until the end of the document.

Could anyone help me out please? I would be very grateful

Thx

Iulius


open my $in, '<', 'file.txt' or die "$! opening input";
open my $out, '>', 'file_ID.txt' or die "$! opening output";

my $counter = 141;

while (<$in>) {
    s/docID="/q{docID="} . $counter++ /eg;
    print $out $_;
}

Uses s///e to replace and increment the counter as instances are found, and processes the file line-by-line instead of reading it all into memory and writing it all back out again, because there's no real reason to do that.


perl regexps support "eval" such that you can do:

s/$oldId/"docid=\"" . $newId++ . "\""/e

where the /e is the eval part that evals the replacement every call.


In your code, you can move the $newID variable inside the for loop :

foreach (@content){
    my $newID = "docID=\"14$counter";
    s/$oldID/$newID/;
    $counter++;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜