BrassMonkey has asked for the wisdom of the Perl Monks concerning the following question:
Here is my text:
>>>cat temp.txt my dog is (red1) my cat is (blue1) my dog is (red2) my cat is (blue2) my dog is (red3) my cat is (blue3) my dog is (red4) my cat is (blue4) my dog is (red5) my cat is (blue5) my dog is (red6) my cat is (blue6)
Here is my code:
#!/usr/bin/perl $mystring = join("", <>); #print $&; print "-----------mystring--------------------------\n"; print $mystring; print "------------variables----------------------------\n"; if ($mystring =~ m/my.*?\((\S*?)\)/g) { #if ($mystring =~ s/my.*?\((\S*?)\)/xxxxxxx/g) { print "$1 \n"; print "-----------mystring again--------------------------\n"; print $mystring; print "-----------------------------------------\n"; }
Here is the output:
>>>>cat temp.txt | perl temp.pl -----------mystring-------------------------- my dog is (red1) my cat is (blue1) my dog is (red2) my cat is (blue2) my dog is (red3) my cat is (blue3) my dog is (red4) my cat is (blue4) my dog is (red5) my cat is (blue5) my dog is (red6) my cat is (blue6) ------------variables---------------------------- red1 -----------mystring again-------------------------- my dog is (red1) my cat is (blue1) my dog is (red2) my cat is (blue2) my dog is (red3) my cat is (blue3) my dog is (red4) my cat is (blue4) my dog is (red5) my cat is (blue5) my dog is (red6) my cat is (blue6) -----------------------------------------
What I can't figure out is how to print each one as it is matched. If I do a global replace, it replaces all of them (commented out that line). So, it is able to match each of them. I'm sure I'm missing an easy perl fuction or special variable. I've looked through Perl bookshelf and also in frequent questions of perlmonks.com
Basically I need to itterate over the matches. I tried a while statement and that doesn't work either.
Matching each line separate with a while <> won't work either. This is just a sample, but the pattern I'm really matching spans multiple lines. The join is necessary for that.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: variables in global match in regex
by davido (Cardinal) on Aug 11, 2004 at 16:07 UTC | |
|
Re: variables in global match in regex
by ikegami (Patriarch) on Aug 11, 2004 at 16:09 UTC | |
|
Re: variables in global match in regex
by Roger (Parson) on Aug 11, 2004 at 16:14 UTC | |
|
Re: variables in global match in regex
by diotalevi (Canon) on Aug 11, 2004 at 16:24 UTC | |
|
Re: variables in global match in regex
by BrassMonkey (Initiate) on Aug 11, 2004 at 16:18 UTC | |
|
Re: variables in global match in regex
by GreyGlass (Sexton) on Aug 11, 2004 at 19:48 UTC |