develooper Front page | perl.beginners | Postings from February 2009

Re: breaking-apart and printing an input file

Thread Previous
From:
Rob Dixon
Date:
February 19, 2009 19:55
Subject:
Re: breaking-apart and printing an input file
Message ID:
499E29B5.2040903@gmx.com
pablo@compugenic.com wrote:
> I have a single input file with entries as follows:
> 
> --snip--
> USER1 [20090101] note
> bla bla bla
> bla bla bla
> 
> USER2 [20090104] note
> bla bla bla
> bla bla bla
> 
> --snip--
> 
> What I'm trying to do is create a single-argument script which displays
> all entries for a given user.
> 
> So calling it as 'filter.pl user1' will print all entries for USER1.
> 
> 
> Here is what I've got so far:
> 
> ---
> my $user = shift;
> 
> # slurp file
> my $file = do {
>     open my $fh, 'inputfile.txt' or die $!;
>     local $/;
>     <$fh>;
> };
> 
> if ( $file =~ /(^$user.*?)^$/smg ) {
>         print $1;
> }
> ---
> 
> Here's my thinking behind the non-functional regex.
> It matches a set of lines starting with a line which begins with $user,
> followed by all non-empty lines, and terminated with an empty line (^$).
> 
> Running my script produces zero output.  My questions are:
> 1. Is there a simpler way to approach/accomplish this?
> 2. If not, what's wrong with my regex?
> 
> 
> 
> Thanks in advance for any help.

I don't kno what results you're getting, but this works fine for me. The only
change I would make is to change the 'if' to a 'while', otherwise only the first
matching record will be found.

There may be an issue with reading the entire file if it is at all large, in
which case I recommend reading in 'paragraph' mode by setting the input record
separator to the null string

  local $/ = "";

after which each read from the file will return a single complete multi-line
record, terminated by a blank line.

HTH,

Rob



use strict;
use warnings;

my $user = 'USER1';

# slurp file
my $file = do {
    local $/;
    <DATA>;
};

if ( $file =~ /(^$user.*?)^$/smg ) {
  print $1;
}

__DATA__
USER1 [20090101] note
bla bla bla
bla bla bla

USER2 [20090104] note
bla bla bla
bla bla bla




Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About