Solved

Perl One Word Per Line

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
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…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

920 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