1

I have a file, and I need to take a count value from the file.

I am storing all the contents of the file in an array and later searching for that particular line (Total number of lines in file is). And again using regex, I am taking out the count.

Code below:

#!/usr/bin/perl

use Data::Dumper;

my @array = <DATA>;

print Dumper(\@array);

my $count = 0;

my @matches = grep { /Total number of lines in file is/ } @array;

foreach (@matches){
    $count = $1 if($_ =~ /Total number of lines in file is :\s*(\d+)\s*/);
}

print "Count:$count\n";

__DATA__
Below is your data file

This is test line A
This is test line B
This is test line C
This is test line D
This is test line E
This is test line F
This is test line G
This is test line H
This is test line I
This is test line J

Total number of lines in file is :10

Here I am using grep and for loop to take the count which is needed to me.

Is there any better way to do this? So, using single grep I can take the count.

3 Answers 3

2

If you don't need to retain all the lines, and you are just interested in the matching line, you can simplify it to:

use warnings;
use strict;

my $count = 0;
while (<DATA>) {
    $count = $1 if /Total number of lines in file is :\s*(\d+)\s*/;
}
print "Count:$count\n";
Sign up to request clarification or add additional context in comments.

Comments

0

Let's find it in another way:

my $str = do { local $/; <DATA>; };

print $1 if($str=~m/Total number of lines in file is :(\d+)/);

1 Comment

This will return the entire line once for every line that matched the pattern and had a number that isn't 0 in the capture group. For the example input that should be 1. That's because grep doesn't map, it just throws away elements where the test returns false.
-1

if you are so keen to use grep instead of toolic's approach, use system grep or backticks :) but you need to understand that firstly you read whole file in an array, and then you "grep" (loop through) all array items and check whether they match the regex. basically, you do the same but with additional memory waste

2 Comments

Agree!! I don't want to waste memory to do this operation.
You don't need to read in the entire file, or shell out to anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.