如何从文件中读取/存储未注释的行到数组?
file.txt
如下所示
request abcd uniquename "zxsder,azxdfgt"
request abcd uniquename1 "nbgfdcbv.bbhgfrtyujk"
request abcd uniquename2 "nbcvdferr,nscdfertrgr"
#request abcd uniquename3 "kdgetgsvs,jdgdvnhur"
#request abcd uniquename4 "hvgsfeyeuee,bccafaderryrun"
#request abcd uniquename5 "bccsfeueiew,bdvdfacxsfeyeueiei"
现在我必须将未注释的行(此脚本中的前3行)读取/存储到数组中。是否可以通过模式匹配字符串名称或任何正则表达式来使用它?如果是的话,我该怎么做?
以下代码将所有行存储到数组中。
open (F, "test.txt") || die "Could not open test.txt: $!\n";
@test = <F>;
close F;
print @test;
我怎么能只为未注释的线做呢?
答案 0 :(得分:3)
如果你知道你的评论将在开头包含#,你可以使用
next if $_ =~ m/^#/
或者使用您拥有的任何变量来读取每一行而不是$_
这匹配行开头的#符号。
至于将其他人添加到数组中,您可以使用push (@arr, $_)
#!/usr/bin/perl
# Should always include these
use strict;
use warnings;
my @lines; # Hold the lines you want
open (my $file, '<', 'test.txt') or die $!; # Open the file for reading
while (my $line = <$file>)
{
next if $line =~ m/^#/; # Look at each line and if if isn't a comment
push (@lines, $line); # we will add it to the array.
}
close $file;
foreach (@lines) # Print the values that we got
{
print "$_\n";
}
答案 1 :(得分:2)
你可以这样做:
push @ary,$_ unless /^#/;END{print join "\n",@ary}'
这会跳过以#
开头的所有行。否则,该行将添加到数组中供以后使用。
答案 2 :(得分:0)
原始程序的最小变化可能是:
open (F, "test.txt") || die "Could not open test.txt: $!\n";
@test = grep { $_ !~ /^#/ } <F>;
close F;
print @test;
但我强烈建议稍微重写以使用当前的最佳做法。
# Safety net
use strict;
use warnings;
# Lexical filehandle, three-arg open
open (my $fh, '<', 'test.txt') || die "Could not open test.txt: $!\n";
# Declare @test.
# Don't explicitly close filehandle (closed automatically as $fh goes out of scope)
my @test = grep { $_ !~ /^#/ } <$fh>;
print @test;