1

コメント解除された行をファイルから配列に読み取り/保存するにはどうすればよいですか?

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;

コメントされていない行だけに対してどうすればよいですか?

4

3 に答える 3

4

コメントの先頭に # が含まれていることがわかっている場合は、使用できます

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";
}
于 2012-08-07T18:45:00.460 に答える
2

あなたがすることができます:

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

で始まる行をスキップします#。それ以外の場合、行は後で使用するために配列に追加されます。

于 2012-08-07T18:48:35.277 に答える
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;
于 2012-08-08T09:03:57.310 に答える