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

dear all, I am a beginner in perl. Can any one help me to solve this? I have a plain text file like this:
alex ;teacher; 1945-12-1; california john; lawyer ; texas peter ;teacher; 1948-01-04
how can i convert this file with perl to plain text like this:
alex;teacher alex; 1945-12-1 alex; california john; lawyer john; texas peter ;teacher peter ; 1948-01-04

Replies are listed 'Best First'.
Re: single line to multiple line
by GrandFather (Saint) on Jun 06, 2009 at 02:57 UTC

    There are inconstancies between your input and output data. I can't determine the rule for handling white space so you will have to figure that much out for yourself.

    The key to your main problem is split. Something like:

    my ($first, @fields) = split ';', $line;

    splits the string in $line into a number of elements in a list then assigns the first element to $first with the rest ending up in @fields.

    Note that we like to see what you have tried and like to be told if you are working on homework so that we can tailor our help to your situation.


    True laziness is hard work
      thank you so much for the instruction
Re: single line to multiple line
by jethro (Monsignor) on Jun 06, 2009 at 03:02 UTC
    use warnings; use strict; while (<>) { chomp; my ($name,@rest)= split(/\s*;\s*/,$_); foreach (@rest) { print $name,'; ',$_,"\n"; } }

    this will print the result to the screen, but if you call this script with

    thisscript old.txt > new.txt

    the output gets stored in the file new.txt. Or you can change the script to explicitly open a file with the open() function and print to it

      It works. Thank you very much. Glad to attend this great perl family.
Re: single line to multiple line
by bichonfrise74 (Vicar) on Jun 06, 2009 at 15:50 UTC
    Another way?
    #!/usr/bin/perl use strict; while (<DATA>) { chomp; my $name; s/^(\w+)\s?;// and $name = $1; for my $i ( split ";" ) { print "$name; $i\n"; } } __DATA__ alex ;teacher; 1945-12-1; california john; lawyer ; texas peter ;teacher; 1948-01-04