开发者

How do I print what was replaced in a substitution operation?

I understand that's a very simple question but I really failed googling it. =(

I've got something like this:

$a =~ s/(\w*)/--word was here--/g;

And I want to put into a log file which words were replaced.

aa 123 bb 234 cc--word was here-- 123 --word was here-- 234 --word was here--

And that's okay, but I want to remember aa, bb and cc and write into a log file. What should I do?

In fact I have a link remover script but I need to remember which links were removed. I tried to simplify my task for you but made it much harder 开发者_如何学JAVAto understand - sorry.


You can use the e modifier which evaluates the right side as an expression:

   $a =~ s/(\w*)/log_it($1), ""/ge;


You can do it in a loop instead of /g;:

my $string = "xxx ; yyy ; zzz";
my @replaced;
while ($string =~ s/(\w+)//) { push @replaced, $1 };
print join(",",@replaced);
# OUTPUT: xxx,yyy,zzz

Please note that \w is a WORD character, not an alphabet one, so it will match digits 0-9 as well. If you only want to match letters, use [[:alpha:]] class


The following stores all captured words into an array:

use strict;
use warnings;
use Data::Dumper;

my $s = 'cat dog';
my @words;
while ($s =~ s/(\w+)//) {
    push @words, $1;
}
print Dumper(\@words);

__END__
$VAR1 = [
          'cat',
          'dog'
        ];

Update: Now that you have added input and output data, it looks like you want to exclude numbers. In that case, you could use [a-zA-Z] instead of [\w].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜