Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Howto print multiple matches in a line

by ashnator (Sexton)
on Nov 11, 2008 at 03:28 UTC ( #722771=perlquestion: print w/replies, xml ) Need Help??
ashnator has asked for the wisdom of the Perl Monks concerning the following question:

I want to print the matches successively in a column but its printing only the first one
Example :-
I am 60 years old I am 60 years old My code prints only 1 occurence not the successive ones. How to do tha +t ?
My code is
#!/usr/bin/perl -w $fn=<>; open(FH, "$fn") || die("Can't open:$!"); while(<FH>) { if($_ =~ /\w\s+\w+\s+\w+\s+\w+\s+\w+/) { print "$_"; } } close FH;

Replies are listed 'Best First'.
Re: Howto print multiple matches in a line
by ikegami (Pope) on Nov 11, 2008 at 03:39 UTC

    Replace if (/.../) with while (/.../g) to get all matches. Use parens around what you want to capture. Use $1 to get what's in the parens, not $_.

    In this, case you can write it concisely as

    while (<FH>) { print( join( "\t", /\w\s+\w+\s+\w+\s+\w+\s+\w+/g ), "\n" ); }
      Thanks a lot dear... ;)
Re: Howto print multiple matches in a line
by motzi (Sexton) on Nov 11, 2008 at 03:39 UTC
    /\w\s+\w+\s+\w+\s+\w+\s+\w+/g
    use 'g' at the end of regex for do that.
Re: Howto print multiple matches in a line
by blazar (Canon) on Nov 11, 2008 at 12:09 UTC
    $fn=<>; open(FH, "$fn") || die("Can't open:$!");

    I personally believe that, incidentally, you will be very likely to die since that will try to open a file whose name ends with a carriage return, and in turn that may well exist on your system (especially if it's some breed of *NIX) but... it's unprobable. Also, "$fn" is called "useless use of quoting variables." Last, didn't mom tell you to always run under strict, except maybe for the simplest one liners?

    --
    If you can't understand the incipit, then please check the IPB Campaign.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://722771]
Approved by ikegami
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2018-05-24 05:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?