develooper Front page | perl.beginners | Postings from January 2002

Re: change the format of file.

Thread Previous
Jonathan E. Paton
January 30, 2002 13:05
Re: change the format of file.
Message ID:

Try this (modifing up as you please):

open (INPUT,  "input.txt" ) or die "Can't open: $!";
open (OUTPUT, "output.txt") or die "Can't open: $!";

my %data;
my $state = 0;

while (<INPUT>) {
    $data{$state++} = $_ if $state == 0;
    $data{$state++} = $_ if $state == 1;
    $data{$state++} = $_ if $state == 2;

    if ($state == 3) {
        print OUTPUT "definition1   $data{0}\n";
        print OUTPUT "definition2\n";
        print OUTPUT "definition3\n";
        print OUTPUT "definition4:$data{1}\n\n";

        # Reset state
        $state = 0;

close (INPUT ) or die "Can't close: $!";
close (OUTPUT) or die "Can't close: $!";


There is obviously many ways of doing this, with various
levels of reliability and readability... I guess someone is
going to do the regex now... :)

This *should* work, and is clean enough looking for a
beginner to understand - maybe.

Jonathan Paton

Do You Yahoo!?
Everything you'll ever need on one web page
from News and Sport to Email and Music Charts

Thread Previous Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About