你会如何在perl中执行以下操作:
for $line (@lines) {
if ($line =~ m/ImportantLineNotToBeChanged/){
#break out of the for loop, move onto the next line of the file being processed
#start the loop again
}
if ($line =~ s/SUMMER/WINTER/g){
print ".";
}
}
Run Code Online (Sandbox Code Playgroud)
更新以显示更多代码,这是我正在尝试做的事情:
sub ChangeSeason(){
if (-f and /.log?/) {
$file = $_;
open FILE, $file;
@lines = <FILE>;
close FILE;
for $line (@lines) {
if ($line =~ m/'?Don't touch this line'?/) {
last;
}
if ($line =~ m/'?Or this line'?/){
last;
}
if ($line =~ m/'?Or this line too'?/){
last;
}
if ($line +~ m/'?Or this line as well'?/){
last;
}
if ($line =~ s/(WINTER)/{$1 eq 'winter' ? 'summer' : 'SUMMER'}/gie){
print ".";
}
}
print "\nSeason changed in file $_";
open FILE, ">$file";
print FILE @lines;
close FILE;
}
}
Run Code Online (Sandbox Code Playgroud)
Tot*_*oto 16
请使用下一个
for my $line (@lines) {
next if ($line =~ m/ImportantLineNotToBeChanged/);
if ($line =~ s/SUMMER/WINTER/g){
print ".";
}
}
Run Code Online (Sandbox Code Playgroud)
for $line (@lines) {
unless ($line =~ m/ImportantLineNotToBeChanged/) {
if ($line =~ s/SUMMER/WINTER/g){
print ".";
}
}
}
Run Code Online (Sandbox Code Playgroud)
一种更简洁的方法是
map { print "." if s/SUMMER/WINTER/g }
grep {!/ImportantLineNotToBeChanged/} @lines;
Run Code Online (Sandbox Code Playgroud)
(我认为我没错。)
只需使用下一个功能。
for $line (@lines) {
if ($line =~ m/ImportantLineNotToBeChanged/){
#break out of the for loop, move onto the next line of the file being processed
#start the loop again
next;
}
if ($line =~ s/SUMMER/WINTER/g){
print ".";
}
}
Run Code Online (Sandbox Code Playgroud)
同样,您可以使用“ last”完成循环。例如:
for $line (@lines) {
if ($line =~ m/ImportantLineNotToBeChanged/){
#continue onto the next iteration of the for loop.
#skip everything in the rest of this iteration.
next;
}
if ($line =~ m/NothingImportantAFTERThisLine/){
#break out of the for loop completely.
#continue to code after loop
last;
}
if ($line =~ s/SUMMER/WINTER/g){
print ".";
}
}
#code after loop
Run Code Online (Sandbox Code Playgroud)
编辑:6/13晚上7点
我拿了你的代码,看着它,重写了一些东西,这就是我得到的:
sub changeSeason2 {
my $file= $_[0];
open (FILE,"<$file");
@lines = <FILE>;
close FILE;
foreach $line (@lines) {
if ($line =~ m/'?Don't touch this line'?/) {
next;
}
if ($line =~ m/'?Or this line'?/){
next;
}
if ($line =~ m/'?Or this line too'?/){
next;
}
if ($line =~ m/\'Or this line as well\'/){
next;
}
if ($line =~ s/(WINTER)/{$1 eq 'winter' ? 'summer' : 'SUMMER'}/gie){
print ".";
}
}
print "\nSeason changed in file $file";
open FILE, ">$file";
print FILE @lines;
close FILE;
}
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助。