Reputation: 35
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 ?
Upvotes: 1
Views: 11847
Reputation: 33370
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";
}
Upvotes: 4
Reputation: 69244
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;
Upvotes: 0
Reputation: 7516
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.
Upvotes: 2