?
Solved

Perl One Word Per Line

Posted on 2014-04-02
4
Medium Priority
?
276 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering 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

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
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

770 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