简体   繁体   中英

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

How can i read/store uncommented lines from file into an array ?

file.txt looks like below

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"

Now i have to read/store the uncommented lines (first 3 lines in this script) into an array. is it possible to use it by pattern matching with string name or any regex ? if so, how can i do this ?

This below code stores all the lines into an array.

open (F, "test.txt") || die "Could not open test.txt: $!\n"; 
@test = <F>; 
close F; 
print @test;

how can i do it for only uncommented lines ?

If you know your comments will contain # at the beginning you can use

next if $_ =~ m/^#/

Or use whatever variable you have to read each line instead of $_

This matches # signs at the beginning of the line. As far as adding the others to an array you can use 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";
}

You could do:

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

This skips any line that begins with # . Otherwise the line is added to an array for later use.

The smallest change to your original program would probably be:

open (F, "test.txt") || die "Could not open test.txt: $!\n"; 
@test = grep { $_ !~ /^#/ } <F>; 
close F; 
print @test;

But I'd highly recommend rewriting that slightly to use current best practices.

# 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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