Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Perl One Word Per Line

Posted on 2014-04-02
4
Medium Priority
?
286 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 1000 total points
ID: 39971980
[^s] should be [^\s] or \S
0
 
LVL 31

Accepted Solution

by:
farzanj earned 1000 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

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…
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
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…
Six Sigma Control Plans

604 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