#!/approot/opt/bin/perl
use strict;
my $file = $ARGV[0];
open FILE, $file or die;
my $line;
while (<FILE>) {
if (m/create unique clustered index \S+ on \S+ \(([^\)]+)\)/) {
$line = $1;
}
s/chargeable_items/$line/;
print;
}
这是我尝试使用的文本文件,但每次尝试替换它时。它用空格替换字符串。
CREATE TABLE t_test
(
system_name varchar(20) NOT NULL,
server_type smallint NOT NULL,
chargeable_system bit NOT NULL,
chargeable_items bit NOT NULL
)
create unique clustered index host_idx on dbo.t_host (system_name, server_type, environment)
create nonclustered index tt_host on dbo.t_host (N.A.)
每当它执行替换运算符时,它会将“chargeable_items”替换为空白值,如下所示
CREATE TABLE t_test
(
system_name varchar(20) NOT NULL,
server_type smallint NOT NULL,
chargeable_system bit NOT NULL,
bit NOT NULL
)
create unique clustered index host_idx on dbo.t_host (system_name, server_type, environment)
create nonclustered index tt_host on dbo.t_host (N.A.)
答案 0 :(得分:4)
您正在while
循环中逐行阅读文件。
在第
行chargeable_items bit NOT NULL
您尚未将$line
设置为任何值,因此chargeable_items
将替换为空值。您只能在行
$line
create unique clustered index host_idx on dbo.t_host (system_name, server_type, environment)
但之后从未使用过$line
,因为该行之后没有chargeable_items
。
工作解决方案是立即读取整个文件,然后进行匹配和替换:
#!/approot/opt/bin/perl
use strict;
my $file = $ARGV[0];
open FILE, $file or die;
local $/;
my $data = <FILE>;
if ($data =~ m/create unique clustered index \S+ on \S+ \(([^\)]+)\)/) {
my $line = $1;
$data =~ s/chargeable_items/$line/;
}
print $data;
此处local $/
在本地将特殊变量$/
(输入记录分隔符)设置为未定义的值,以便<FILE>
一次读取整个文件,而不是逐行读取是正常的行为。