我在文件中有以下行..
- VSSC!.extra196 + NET VSSC!
+ DIRECTION INOUT
+ USE GROUND
+ LAYER BA ( 0 0 ) ( 1500 80870 )
+ PLACED ( 1055560 1571000 ) N ;
- VSSC!.extra197 + NET VSSC!
+ DIRECTION INOUT
+ USE GROUND
+ LAYER BA ( 0 0 ) ( 1500 80870 )
+ PLACED ( 1055560 1571000 ) N ;
- VSSC!.extra198 + NET VSSC!
+ DIRECTION INOUT
+ USE GROUND
+ LAYER BA ( 0 0 ) ( 1500 80870 )
+ PLACED ( 1043560 1571000 ) N ;
我想在第3行添加第一行..
例如:` - VSSC!.extra198 + NET VSSC! +使用地面+特殊
通过使用匹配运算符,我能够捕获第一行和第三行。下一个任务是,如何追加并添加一个名为+SPECIAL
的单词?
use warnings;
my @array;
open(my $fh, "<", "sample.txt") or die "Failed to
open file: $!\n";
while(<$fh>) {
my $i; chomp; push @array, $_;
}
close $fh;
for(i=0;i<3;i++)
{
print "$array[i] $array[i+2] +SPECIAL \n";
}
答案 0 :(得分:1)
对于这样的任务,在第一步中形成线组很有用。然后,在第二个循环中,您可以访问每个组,并且可以轻松地重新排列或修改:
use strict;
use warnings;
# First, form the groups
# Each group starts with a line matching a certain pattern, e.g. /^\-/
my @groups = ();
my $current;
foreach my $line (<DATA>) {
chomp $line;
next unless $line;
if ($line =~ /^\-/) {
push @groups, $current if $current;
$current = [];
}
push @$current, $line;
}
push @groups,$current if (scalar @$current > 0); # last group
# Now you have the groups, you can manipulate the output
# and print it comfortably in a modified form
foreach (@groups) {
my @current = @{ $_ };
foreach my $i (0..$#current) {
if ($i==0) {
print "$current[$i] $current[$i+2] +SPECIAL\n";
}
else {
print "$current[$i]\n";
}
}
}
__DATA__
- VSSC!.extra196 + NET VSSC!
+ DIRECTION INOUT
+ USE GROUND
+ LAYER BA ( 0 0 ) ( 1500 80870 )
+ PLACED ( 1055560 1571000 ) N ;
- VSSC!.extra197 + NET VSSC!
+ DIRECTION INOUT
+ USE GROUND
+ LAYER BA ( 0 0 ) ( 1500 80870 )
+ PLACED ( 1055560 1571000 ) N ;
- VSSC!.extra198 + NET VSSC!
+ DIRECTION INOUT
+ USE GROUND
+ LAYER BA ( 0 0 ) ( 1500 80870 )
+ PLACED ( 1043560 1571000 ) N ;
为了使其独立,我将样本数据作为__DATA__
放在脚本的末尾。当然,您也可以从文件中读取行,这需要对脚本的第一部分进行一些细微的更改。
答案 1 :(得分:1)
这比听起来容易 - 您的数据有分隔符;
。
所以你可以设置$/
并使用它。
#!/usr/bin/env perl
use strict;
use warnings;
local $/ = ";\n";
while ( <DATA> ) {
chomp;
my @chunk = split /\n/;
print join ( " ", @chunk[0,2], " + SPECIAL" ),"\n";
}
__DATA__
- VSSC!.extra196 + NET VSSC!
+ DIRECTION INOUT
+ USE GROUND
+ LAYER BA ( 0 0 ) ( 1500 80870 )
+ PLACED ( 1055560 1571000 ) N ;
- VSSC!.extra197 + NET VSSC!
+ DIRECTION INOUT
+ USE GROUND
+ LAYER BA ( 0 0 ) ( 1500 80870 )
+ PLACED ( 1055560 1571000 ) N ;
- VSSC!.extra198 + NET VSSC!
+ DIRECTION INOUT
+ USE GROUND
+ LAYER BA ( 0 0 ) ( 1500 80870 )
+ PLACED ( 1043560 1571000 ) N ;
打印:
- VSSC!.extra196 + NET VSSC! + USE GROUND + SPECIAL
- VSSC!.extra197 + NET VSSC! + USE GROUND + SPECIAL
- VSSC!.extra198 + NET VSSC! + USE GROUND + SPECIAL