1

Here is what I have:

open INFILE,    "<",    "$inputfile";
open OUTFILE,   ">",    "$outfile";
@array = qw{ Element1 Element2 };
        if ( ! open INFILE, "<", "$inputfile") {
                die "Cannot open INFILE: $!";
        }
while (<INFILE>) {
         if ($_ =~ m/(str1)|(str2)/sg) {
              chomp;
              $regex = $_;
                   foreach $list (@array) {
                            print OUTFILE "\$list is $list\n";
                            print OUTFILE "String is $regex\n";
                    }
          }
}

close INFILE;
close OUTFILE;

What I am getting is:

\$list is ELEMENT 1
String is str1
\$list is ELEMENT 2
String is str1
\$list is ELEMENT 3
String is str1

I want this output:

\$list is ELEMENT 1
String is str1
\$list is ELEMENT 2
String is str2
\$list is ELEMENT 3
String is str3
4

1 回答 1

0

这是每个脚本顶部应该使用的内容:

use warnings; use 5.012; # (or whatever version you are using)

如果您use的版本大于5.010,您将获得各种好东西,例如自动strict性和say功能。

一个人去很危险。随身携带错误处理:

open my $filehandle, "<", $filename or die "Can't open $filename: $!";

使用openwithoutdie可能会招致 bug。

我会将您的while-loop 编码为:

while (my $line = <$infile>) {
  chomp $line;
  if ($line =~ /str[12]/) {
    foreach my $element (@array) {
      say $outfile "I am at element $element";
      say $outfile "The string is $line";
    }
  }
}

这个↑有点美化和精简,但和你在帖子里写的差不多。如果你的文件很小,你甚至可以做一个

foreach my $line (grep {chomp; /str[12]/} <$infile>) {
  foreach my $element (@array) {...}
}

现在我们有了相当干净的代码,我们可以考虑您的问题:

您提供的代码不会产生您声称的输出:既不@array包含ELEMENT 3,您的正则表达式也无法匹配str3。此外,对于每个匹配的字符串,打印@array. print "\$"打印$而不是\$

我将假设您要匹配str后跟一个数字,并且您要从@array相应位置的元素中选择该元素。

# selecting the lines
my @lines;
while (<$infile>) {
  chomp;
  push @lines, [$_ => $1-1] if /str(\d)/ and $1 > 0; # avoid off-by-one errors
  # push @lines, [$1 => $2-1] if /(str(\d))/ and $2 > 0;
}

# clever initialization
my @array = map {"ELEMENT $_"} 1..9;

# print out the report
foreach my $line (@lines) {
  my ($string, $index) = @$line;
  my $element = $array[$index];
  say $outfile "I have $element";
  say $outfile "String is $string";
}
# folding the loops into one is left as an exercise for the reader

现在如果输入是

str1
str2
foo
str3
Here is str8 among other things!
bar
str45
baz

输出将是

I have ELEMENT 1
String is str1
I have ELEMENT 2
String is str2
I have ELEMENT 3
String is str3
I have ELEMENT 8
String is Here is str8 among other things!
I have ELEMENT 4
String is str45
于 2012-10-30T19:47:15.243 回答