Solved

Perl One Word Per Line

Posted on 2014-04-02
4
258 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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
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…
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…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

707 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now