Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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
    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?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://722771]
Approved by ikegami
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2021-12-03 06:42 GMT
Find Nodes?
    Voting Booth?
    R or B?

    Results (28 votes). Check out past polls.