我是 Perl 的新手。我要做的是打开一个文件列表,在每个文件中增加三个不同的变量,保存文件,然后关闭。
变量看起来像这样
This_Is_My_Variable03
This_Is_My_Variable02
This_Is_My_Variable01
以 01 结尾的变量在文件中多次出现。变量有时是字符串的一部分。变量的This_Is_My_Variable
部分永远不会改变。
谢谢。
这可能不是最好的解决方案,但它有效
#!perl=C:\IBM\RationalSDLC\ClearCase\bin\perl
use warnings;
use strict;
use Tie::File;
tie my @data, 'Tie::File', 'myfile.txt' or die $!;
s/(This_Is_My_Variable)(\d+)+/$1.++($_=$2)/eg for @data;
untie @data;
感谢 Borodin 让我开始Tie::File
:这绝对有帮助。
使用while循环的第二种解决方案
#!perl=C:\IBM\RationalSDLC\ClearCase\bin\perl
use warnings;
#use strict;
sub inc {
my ($num) = @_;
++$num;
}
open(FILE, "myfile.txt") || die $!;
$i = 0;
while (<FILE>) {
$string = $_;
if (/This_Is_My_Variable../) {
$string =~ s/(This_Is_My_Variable)(\d+)+/$1.++($_=$2)/eg;
print "$string \n";
$i++;
}
else {
print "$string \n";
}
}
close FILE;