Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > Perl Misc > slurp with pattern match

Reply
Thread Tools

slurp with pattern match

 
 
bjlockie
Guest
Posts: n/a
 
      09-20-2012
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?
 
Reply With Quote
 
 
 
 
Rainer Weikusat
Guest
Posts: n/a
 
      09-20-2012
bjlockie <(E-Mail Removed)> 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.


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



 
Reply With Quote
 
 
 
 
J. Gleixner
Guest
Posts: n/a
 
      09-20-2012
On 09/20/12 14:56, bjlockie wrote:
> 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 );
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
How to slurp/get the content of a URI? Stefan Ram Java 13 07-27-2008 10:05 PM
Re: can slurp do this? Jürgen Exner Perl 0 07-16-2008 01:51 PM
Re: The slurp heard round the world Rebecca Computer Security 6 11-15-2005 03:51 PM
Re: The slurp heard round the world Rebecca Computer Security 3 11-12-2005 04:57 PM



Advertisments