coco has asked for the wisdom of the Perl Monks concerning the following question:

Hi

What I want to achieve is to open an input file & open an output file, parse the input file until i match a piece of text then extract the text to the output file. The input file will look like this:

name: John Doe
23
name: Jane Doe
37
name: Joe Doe
12

i want to match any occurance of name and take that line along with the following line out of the input file and write it to the ouput file. Can anyone suggest the best way to achieve this. I can produce the code that will open both files, match the string name and write that line out, but i need to be able to take the next line too.
Thanks.

Replies are listed 'Best First'.
Re: Input Output Question
by merlyn (Sage) on Jul 06, 2009 at 16:17 UTC
    Sigh. School must be back in session again for some people. I call homework.

    -- Randal L. Schwartz, Perl hacker

    The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

Re: Input Output Question
by davorg (Chancellor) on Jul 06, 2009 at 15:40 UTC

    Something a bit like this, perhaps (untested):

    #!/usr/bin/perl use strict; use warnings; my $name = shift or die "No name given\n"; while (<>) { if (/name: $name/) { print; print scalar <>; } }

    This reads from STDIN and writes to STDOUT. I think that's often more flexible than opening your own filehandles. You can use standard Unix redirection tricks to read from and write to specific files.

    --

    See the Copyright notice on my home node.

    Perl training courses

Re: Input Output Question
by JavaFan (Canon) on Jul 06, 2009 at 16:01 UTC
    I wouldn't bother using Perl to write my own wheel. Finding and printing matches is a task for grep Code reuse doesn't stop at using a module from CPAN.
    grep -A 1 'Jane Doe' input > output
Re: Input Output Question
by Transient (Hermit) on Jul 06, 2009 at 15:35 UTC
    One way to do it would be to set a flag as the lines come across that match the name. Once you come to the next iteration, if that flag is true, grab the value you need and reset the flag to false.
Re: Input Output Question
by bichonfrise74 (Vicar) on Jul 06, 2009 at 20:24 UTC
    Take a look at this...
    #!/usr/bin/perl use strict; while (<DATA>) { print if ( /^name:\s\w+\s?\w+/ ... /^.*$/ ); } __DATA__ name: John Doe 23 name: Jane Doe 37 test: asdas name: Joe Doe 12
      Just looking at this, would you be able to break down exactly what is happening please. Thanks
        Take a look at the Range Operators documentation. This is one technique for grabbing a range of lines.