http://qs321.pair.com?node_id=722771

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 (Patriarch) 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.