如何在perl中的文件句柄循环内迭代数组元素

时间:2012-10-30 18:32:34

标签: perl

这就是我所拥有的:

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;

我得到的是:

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

我想要这个输出:

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

1 个答案:

答案 0 :(得分:0)

这是应该在每个脚本的顶部使用的东西:

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

如果use版本大于5.010,您可以获得各种好处,例如自动strictsay功能。

独自一人是危险的。与您一起处理错误:

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

使用不open的{​​{1}}可能是对错误的邀请。

我会将您的die - 循环编码为:

while

这个↑有点美化和精简,但相当于你在帖子中写的内容。如果你的文件很小,你甚至可以做一个

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