aurora26 has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I'm new to this forum and i'm learing perl.... on the way i got a doubt....I needed a script which stores all the numbers, which is followed by "MAN", in a .txt file. For eg: The file may contains statements like MAN:113 some other test 666.... MAN 231,456 TEXTtext alpha Man 999 etc..77789 etc man 111,222,333 Here my script should store only those numbers followed by "man"(case insensitive), i,e 113,231,456,999,111,222,333 (not 666,77789) How can i do that? I wrote script which does part of it but cant recognize 222 in man 111,222. :(
$line = <FILE>; $i=0; $Count=0; @Temp_array=0; while ($line ne "") { $_=$line; if (/MAN [0-9]+/ || /MAN: [0-9]+/ ) { $Temp_array[$i]=$&; $_=$Temp_array[$i]; if(/ [\d]*/) { $Bug_num_array[$Count]=$&; } $i++; $Count++; } $line = <FILE>; } close FILE;
please help me to solve this...Thank u

Replies are listed 'Best First'.
Re: regular expression to match in between digits..
by AnomalousMonk (Archbishop) on Dec 28, 2011 at 08:25 UTC
    >perl -wMstrict -le "my $s = ',42 MAN:113 some other test 666.... MAN 231,456 TEXT' . 'text alpha Man 999 etc..77789 etc man 111,222,333' ; print qq{[[$s]]}; ;; my $man = qr{ (?i) man :? }xms; ;; my @n = $s =~ m{ (?: \G (?<! \A) \s* , | $man) \s* (\d+) }xmsg; printf qq{'$_' } for @n; " [[,42 MAN:113 some other test 666.... MAN 231,456 TEXTtext alpha Man 9 +99 etc..77789 etc man 111,222,333]] '113' '231' '456' '999' '111' '222' '333'

    See perlre and the sub-section '\G assertion' in the Regexp Quote Like Operators section (and, in general, the whole Regexp Quote Like Operators section) in perlop.

Re: regular expression to match in between digits..
by TJPride (Pilgrim) on Dec 28, 2011 at 19:32 UTC
    A little more wordy than the other solution, but in this case perhaps easier to understand.

    use strict; use warnings; my @matches; while (<DATA>) { # MAN followed by at least one number while (m/MAN((\D\d+)+)/ig) { # Trim leading non-digit, split rest of number string into ind +ividual numbers my $n = $1; $n =~ s/^\D//; push @matches, split /\D/, $n; } } print join ',', @matches; __DATA__ MAN:113 some other test 666.... MAN 231,456 TEXT text alpha Man 999 etc.. 77789 etc man 111,222,333

    Output: 113,231,456,999,111,222,333