繁体   English   中英

如何使用perl从文件中读取特定行并存储在数组中?

[英]How to read specific lines from file and store in an array using perl?

如何从文件读取/存储未注释的行到数组?

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;

我该如何仅对未注释的行执行此操作?

如果您知道注释的开头将包含#,则可以使用

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

您可以这样做:

push @ary,$_ unless /^#/;END{print join "\n",@ary}'

这将跳过以#开头的任何行。 否则,该行将添加到数组中以备后用。

对原始程序的最小更改可能是:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM