Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to write each word in a text file on a new line

Status
Not open for further replies.

deepagovind

Technical User
Jan 26, 2004
4
0
0
US
Hi,

I am new perl user. I wish to write each word in a text file separated by spaces on to a new line.
e.g: temp.txt:

This is a nice forum
Good learning Perl

Output:

This
is
a
nice
forum
Good
learning
perl

My script:
#!/usr/intel/bin/perl
open LIST, "temp" or die "$!\n";
open (NEW, ">new") or die "$! error trying to overwrite";
@lines = <LIST>;
#$line =~ s/ /\n/g;
close(LIST);
#print &quot;@lines&quot;; # a space is inserted between elements
$&quot; = &quot;\n&quot;; print &quot;@lines\n&quot;;
close(NEW);


Your suggestions gratefully appreciated.

Thnak you.
 
The following should do the trick. Comments added for clarification.
Code:
$file = &quot;temp.txt&quot;;
$RecSep = $/; # Save input record separator
undef($/); # Undefine input record separator
open(F, $file) or die &quot;Can't open $file: $!\n&quot;;
$contents = <F>; # Read all of file into a string
close(F);
$contents =~ s/\s+/\n/g; # Replace space(s) with new line
$new = &quot;new.txt&quot;;
open(N, &quot;>$new&quot;) or die &quot;Can't open $new: $!\n&quot;;
print N $contents; # Print modified contents to new file
close(N);
$/ = $RecSep; # Put the input record separator back to its original value
 
For simplicity, reading from STDIN and writing to STDOUT -- you can just substitute filehandles appropriately.

[tt]# read lines one by one, assigning to $_
while (<>) {
# get rid of the newline in $_
chomp;

# split(/s+/) takes the line read without the newline
# (still in $_) and splits it into an array on space boundaries (one or many)
#
# join(&quot;\n&quot;, ...) makes a single string, using newline as the join between elements
# of the array we just created with split
print join(&quot;\n&quot;, split(/\s+/));

# print a newline, since the last word of the previous line won't have one
print &quot;\n&quot;;
}[/tt]
 
you should really use the split(&quot; &quot;) because the /\s+/ will put any leading spaces on the line as an element of the list ... the &quot; &quot; understands tabs, spaces etc too and wont put the leading spaces as an element:

Code:
$string = &quot;   a b c&quot;;
@list=	split(/\s+/,$string);
foreach $i (@list) {print &quot;i > $i\n&quot;}

yeilds:
i >
i > a
i > b
i > c


while :

Code:
$string = &quot;   a b c&quot;;
@list=	split(&quot; &quot;,$string);
foreach $i (@list) {print &quot;i > $i\n&quot;}

gives:

i > a
i > b
i > c
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top