Home: Perl Programming Help: Beginner:
Split file content



Stefanik
User

Dec 3, 2012, 2:08 AM


Views: 3514
Split file content

Hi to all,
I'm new here.

I've a little problem with a perl script.
I have a file with many information. with ":" in it.
For example:
word1Line1:word2Line1:word3Line1
word1Line2:word2Line2
....

I should have an output file with Word splitted each for new line:
word1Line1
word2Line1
word3Line1
<separator>
word1Line2
word2Line2

I try to split it with following loop, without any output:


Code
open (myfile, 'test.log'); 
while (<myfile>){
$SplitVar = split (':', <myfile>);
}
print $SplitVar;
close (myfile);



Jurafsky
Novice

Dec 3, 2012, 3:13 AM


Views: 3513
Re: [Stefanik] Split file content

supposing you have this line in your file


Code
$line = "word1Line1:word2Line1:word3Line1  
word1Line2:word2Line2 ";
@txt = split (/:/, $line);


then you need a for loop to display it

Code
for ($i = 0; $i < @txt; $i++) { 
print "$txt[$i]\n";
}



Stefanik
User

Dec 3, 2012, 5:02 AM


Views: 3512
Re: [Jurafsky] Split file content

Many thanks Jurafsky,
how should I change split command to have following syntax, with ":" at the end?

word1line1:
word2line1:
.....

Thanks to you.


Laurent_R
Veteran / Moderator

Dec 3, 2012, 10:37 AM


Views: 3504
Re: [Stefanik] Split file content

You mean that you want to keep the : at the end of your line?

Well, split on ':' will remove it, so either you add it back after the split, or you use another syntax such as:


Code
$line = " word1line1: word1line2: word1line3:"; 
$line =~ s/:/:\n/g;
print $line;


which will print:

Code
word1line1: 
word1line2:
word1line3:



Stefanik
User

Dec 3, 2012, 1:54 PM


Views: 3499
Re: [Laurent_R] Split file content

Thanks Laurent. I was confuse on it Blush