- 论坛徽章:
- 0
|
我的代码太多了,有50行。还是贴上来吧。- #!perl
- use strict;
- use warnings;
- use 5.010;
- use YAML qw(Dump);
- our $cluster_id_str = {};
- my $str = '{aaa:ddd},{ddd:eee:fff:ggg},{abc:abc:abc},{bdc:xef:tks}';
- my $regexp = '{(?<key>\w+):(?<value>\w+):(?<flag>\w+)}';
- $str =~ s/($regexp)/replace_cluster_id($1,$regexp)/xmsge;
- say $str;
- # say Dump($cluster_id_str);
- # replace every captured str with cluster id str
- # If regexp have mulpity named capture structure,
- # could replace in same time
- sub replace_cluster_id {
- my ($match_str, $regexp_str) = @_;
- my $re_regexp_cluster = '\(\?\<([a-z_]+)\>';
- my @cluster_name = $regexp_str =~ /$re_regexp_cluster/xmsg;
- my @capture_str = $match_str =~ /$regexp_str/xmsg;
- my @location_from = @-;
- shift @location_from;
- # Error check: if have error structure of regexp
- if ((scalar @cluster_name != scalar @capture_str) or
- (scalar @location_from != scalar @cluster_name)) {
- say "Regexp $regexp_str have no name capture structure";
- exit;
- }
- foreach my $i (reverse(0 .. $#cluster_name)) {
- my $from = $location_from[$i];
- my $length = length $capture_str[$i];
- my $str = $capture_str[$i];
- my $replace_id = apply_cluster_id($cluster_name[$i], $str);
- substr($match_str, $from, $length, $replace_id);
- }
- return $match_str;
- }
- sub apply_cluster_id {
- my ($flag, $str) = @_;
- state $count = 0;
- $count++;
- my $id = sprintf("!%04d$flag!", $count);
- $cluster_id_str->{$id} = $str;
- return $id;
- }
复制代码 |
|