Solved

Perl One Word Per Line

Posted on 2014-04-02
4
266 Views
Last Modified: 2014-04-02
I am looking to take a long text file, and break it up, so that only one word appears on each line. I have something that breaks up on white space, but there is a flaw in it. The desired output would turn:

This is a test.

into:

This
is
a
test.

This is what I am presently using:

#!/usr/bin/perl

{
  local $/=undef;
  open FILE, "text.txt" or die "Couldn't open file: $!";
  $string = <FILE>;
  close FILE;
}

while($string =~ /([^s]+)/g) {
        print "$1\n";
}

Open in new window

0
Comment
Question by:stakor
  • 2
4 Comments
 
LVL 31

Expert Comment

by:farzanj
ID: 39971978
This is a one liner

perl -pe 's/\s+/\n/g' filename

Open in new window

0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 250 total points
ID: 39971980
[^s] should be [^\s] or \S
0
 
LVL 31

Accepted Solution

by:
farzanj earned 250 total points
ID: 39971991
As Ozo said, you missed back slash

Here's another version of the code above

#!/usr/bin/perl
#
#
use warnings;
use strict;


while(<>)
{
    s/\s+/\n/g;
    print;
}

Open in new window

0
 

Author Closing Comment

by:stakor
ID: 39973471
First working solution was posted by Faranj, Ozo helped change the code into a working set however, so I am splitting the points. Thanks everyone.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question