Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: How can I read and print lines that has only one word from a file

by cjf (Parson)
on Jul 15, 2002 at 03:35 UTC ( #181687=note: print w/ replies, xml ) Need Help??


in reply to How can I read and print lines that has only one word from a file

So you want to open a file and print out all lines that only contain one word? If so, this should work:

open FILE, "file.txt" or die $!; while (<FILE>) { chomp; print "$_\n" if $_ =~ /^(\w+)$/; } close FILE;

Let me know if you have any questions.

Update: ++'s to tadman for the improvements below.


Comment on Re: How can I read and print lines that has only one word from a file
Download Code
Re^2: How can I read and print lines that has only one word from a file
by tadman (Prior) on Jul 15, 2002 at 04:17 UTC
    Or alternatively, being a little more accomodating:
    while (<>) { print if (/^\s*\S+\s*$/); }
    You can call this with either one file, or as many as you like. The double-angle-brackets just read in anything from @ARGV. Further, it looks for a single group of "non-space" characters. This includes things with punctuation and such.
Re: Re: How can I read and print lines that has only one word from a file
by Anonymous Monk on Jul 15, 2002 at 04:30 UTC
    Yes I have a question. Does /^(\w+)$/ mean that lines that start with one word or contain one word?
      It means, literally, "start of line(^), followed by one-or-more word-characters(\w+), followed by end of line($)". This is one possible definition of "one word on line".

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://181687]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2015-07-05 10:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (61 votes), past polls