perl, если строка соответствует регулярному выражению, игнорировать строку и перейти к следующей строке в файле - PullRequest
5 голосов
/ 10 июня 2011

Как бы вы сделали следующее в 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 ".";
    }
}

Обновлено, чтобы показать больше кода, вот что я пытаюсь сделать:

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;
    }
}

Ответы [ 4 ]

15 голосов
/ 10 июня 2011

Просто используйте следующий

for my $line (@lines) {
    next if ($line =~ m/ImportantLineNotToBeChanged/);
    if ($line =~ s/SUMMER/WINTER/g){
        print ".";
    }
}
4 голосов
/ 10 июня 2011

Просто используйте следующую функцию.

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 ".";
  }
}

Аналогично, вы можете использовать «последний» для завершения цикла.Например:

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

Редактировать: 7 вечера 6/13

Я взял ваш код и посмотрел его, переписал некоторые вещи, и вот что я получил:

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;
}

Надеюсь, это поможет некоторым.

4 голосов
/ 10 июня 2011
for $line (@lines) {
    unless ($line =~ m/ImportantLineNotToBeChanged/) {
        if ($line =~ s/SUMMER/WINTER/g){
            print ".";
        }
    }
}

Более краткий метод -

map { print "." if s/SUMMER/WINTER/g }
    grep {!/ImportantLineNotToBeChanged/} @lines;

(думаю, я понял это правильно.)

2 голосов
/ 10 июня 2011

Если я не понимаю вас, ваш "разрыв цикла for, переход на следующую строку ... [и] запуск цикла снова" - это просто сложный способ сказать "пропустить тело цикла для этой итерации".

for $line (@lines) {
  unless (($line =~ m/ImportantLineNotToBeChanged/) {
    if ($line =~ s/SUMMER/WINTER/g) {
      print ".";
    }
  }
}
...