Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

slurp with pattern match

23 views
Skip to first unread message

bjlockie

unread,
Sep 20, 2012, 3:56:43 PM9/20/12
to
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?

Rainer Weikusat

unread,
Sep 20, 2012, 4:05:14 PM9/20/12
to
bjlockie <bjlo...@lockie.ca> writes:
> 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.
You could use grep here:

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



J. Gleixner

unread,
Sep 20, 2012, 6:06:34 PM9/20/12
to
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 );

Ben Morrow

unread,
Sep 20, 2012, 7:12:40 PM9/20/12
to

Quoth "J. Gleixner" <glex_n...@qwest-spam-no.invalid>:
> On 09/20/12 14:56, bjlockie wrote:
> >
> > I want to slurp only lines that match a pattern.
> > Can I still slurp or do I need to loop each line?
<snip>
>
> 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>;

This variant reads all the lines of the file into a list before passing
that list to grep, so it isn't suitable for huge files either.

The most memory-efficient option is

while (<$out>) {
/blah/ or next;
# process the line immediately, then throw it away
}

Ben

0 new messages