iterating with a substitution

R

RedGrittyBrick

I'm feeling stupid. How can I combine the substitution and matching in
the example below?

-----------------8<--------------
#!/usr/bin/perl
use strict;
use warnings;

while (<DATA>) {
while (/<(\d+)>/g) { #1
print "$1 removed\n";
}
s/<\d>//g; #2
}

__DATA__
aaa aaa aaa aaa aaa aaa
bbb b <12> bb bbbb bbbb
cccc ccc cc cc cc ccccc
dd dd <22> dd <99> dd d
eee eee eee eee eee eee
-----------------8<--------------

12 removed
22 removed
99 removed


What #1 would eliminate the need for #2?
 
R

Ron Bergin

I'm feeling stupid. How can I combine the substitution and matching in
the example below?

-----------------8<--------------
#!/usr/bin/perl
use strict;
use warnings;

while (<DATA>) {
   while (/<(\d+)>/g) {     #1
     print "$1 removed\n";
   }
   s/<\d>//g;               #2

}

__DATA__
aaa aaa aaa aaa aaa aaa
bbb b <12> bb bbbb bbbb
cccc ccc cc cc cc ccccc
dd dd <22> dd <99> dd d
eee eee eee eee eee eee
-----------------8<--------------

12 removed
22 removed
99 removed

What #1 would eliminate the need for #2?

while (<DATA>) {
print "$1 removed\n" while s/<(\d+)>//;
}
 
S

sln

I'm feeling stupid. How can I combine the substitution and matching in
the example below?

-----------------8<--------------
#!/usr/bin/perl
use strict;
use warnings;

while (<DATA>) {
while (/<(\d+)>/g) { #1
print "$1 removed\n";
}
s/<\d>//g; #2
}

__DATA__
aaa aaa aaa aaa aaa aaa
bbb b <12> bb bbbb bbbb
cccc ccc cc cc cc ccccc
dd dd <22> dd <99> dd d
eee eee eee eee eee eee
-----------------8<--------------

12 removed
22 removed
99 removed


What #1 would eliminate the need for #2?

use strict;
use warnings;

{
local $/ = 4096;
(my $str=<DATA>) =~ s/<(\d+)>(?{ print "$^N removed\n" })//g;
print "\n",$str;
}

__DATA__
aaa aaa aaa aaa aaa aaa
bbb b <12> bb bbbb bbbb
cccc ccc cc cc cc ccccc
dd dd <22> dd <99> dd d
eee eee eee eee eee eee

-sln
 
S

sln

Why use an experimental feature when perfect standard idioms are known?

M4

In the regex? Which is the experimental feature and what does that mean
to you? Did it work on your build?

Which of these extended features are experimental, why or why not?

Extended Patterns:
(?#text)
(?pimsx-imsx)
(?:pattern)
(?imsx-imsx:pattern)
(?|pattern)
(?=pattern)
(?!pattern)
(?<=pattern) \K
(?<!pattern)
(?'NAME'pattern)
(?<NAME>pattern) ) >>
\k<NAME>
\k'NAME'
(?{ code })
(??{ code })
(?PARNO) (?-PARNO) (?+PARNO) (?R) (?0)
(?&NAME)
(?(condition)yes-pattern|no-pattern)
(?(condition)yes-pattern)
(?>pattern)

-sln
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top