slurp with pattern match

B

bjlockie

my @checkOutput = ();
if (open( FILE, $inputFilePath . '/checkOutput' )) {
@checkOutput = <FILE>;
close( FILE );
}

I want to slurp only lines that match a pattern.
Can I still slurp or do I need to loop each line?
 
R

Rainer Weikusat

bjlockie said:
my @checkOutput = ();

Perl variables don't need to be initialized explicitly. In some pretty
accidental looking circumstances, perl might print warnings when an
automatic conversion of a scalar without a value to a string or an
integer occurs. But even this doesn't apply here because the value of
@checkOutput is an empty array. There's no point in emptying that by
assigning an empty list to it.

if (open( FILE, $inputFilePath . '/checkOutput' )) {
@checkOutput = <FILE>;
close( FILE );
}

I want to slurp only lines that match a pattern.
Can I still slurp or do I need to loop each line?

You could use grep here:

@checkOutput = grep { /pattern/ } <FILE>;
 
J

J. Gleixner

my @checkOutput = ();
if (open( FILE, $inputFilePath . '/checkOutput' )) {
@checkOutput =<FILE>;
close( FILE );
}

I want to slurp only lines that match a pattern.
Can I still slurp or do I need to loop each line?

Many ways..

Using File::Slurp.

use File::Slurp;
my $file = "$inputFilePath/checkOutput";
my @checkOutput = grep { /blah/ } read_file( $file );


or maybe the file is really large and you don't want to 'slurp'..

my $file = "$inputFilePath/checkOutput";
open( my $out, '<', $file ) || die "Can't open $file: $!";
my @checkOutput;
while( <$out> )
{
push( @checkOutput, $_ ) if /blah/;
}
close( $out );

or make that while a bit more compact..

my @checkOutput = grep { /blah/ } <$out>;

or if you're on a Unix machine and your pattern can be done
using grep from the OS.

open( FH, "/bin/grep 'blah' $inputFilePath/checkOutput |" )
|| die "Can't grep $file: $!";
my @checkOutput = <FH>;
close( FH );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top