-1

在以下两种情况下,如何使用 Perl 修改文件(将以下内容作为其内容的一部分)。字符串的正确位置(写在正确的行中,从第一个开始有 2 个空格)很重要。此外,在 ${P}/TEST 中的以下 TEST 不是恒定的,并且在运行过程中会发生变化;所以我们不应该对它使用匹配函数。原始文件是:

! List of Campaigns
! -----------------
CAMPAIGN 1
  "${P}/TEST"
  ## widget = uniline

1) 在“${P}/TEST”下添加另一个带双引号的字符串,例如“${P}/XXXXXX”(程序中之前定义了XXXXXX)。注意活动的数量!所以它会变成:

! List of Campaigns
! -----------------
CAMPAIGN 2
  "${P}/TEST"
  "${P}/XXXXXX"
  ## widget = uniline

2)替换“${P}/XXXXXX”而不是“${P}/TEST”。所以它会变成:

! List of Campaigns
! -----------------
CAMPAIGN 1
  "${P}/XXXXXX"
  ## widget = uniline
4

1 回答 1

0

这应该给你一个想法。我看到了需要add_campaignreplace_campaign操作,然后从那里拿走了它。您的数据在__DATA__伪文件中。

程序输出:

$ campaigns.pl
! List of Campaigns
! -----------------
CAMPAIGN 3
  "${P}/TEST"
  "${P}/MONKEY"
  "${P}/BLUE"
  ## widget = uniline

节目来源:

#!/usr/bin/perl

use strict;
use warnings;

### main program

# read entire file contents into $data
my $data = do { local $/; <DATA> };

# make an entry in %campaigns for each campaign in $data. Each entry's key 
# is the campaign's name. Its value is irrelevant. We use 1.
my %campaigns;
my $last_campaign_offset;   # index of last campaign found
while ( $data =~ /  "\$\{P\}\/(\w+)"/g ) {
  $campaigns{$1}        = 1;
  $last_campaign_offset = index($data, $');
}

add_campaign('CAMEL');
add_campaign('BLUE');
add_campaign('TEST');   # no-op: campaign already exists
replace_campaign('CAMEL', 'MONKEY');
print $data;


### subroutines

### append a new '  ${P}/FOO' campaign to the data
sub add_campaign {
  my $new_cpn = shift;
  return if exists $campaigns{$new_cpn};

  $new_cpn = qq[\n  "\${P}/$new_cpn"];
  substr($data, $last_campaign_offset) 
    = $new_cpn . substr($data, $last_campaign_offset);
  $last_campaign_offset += length($new_cpn);

  # lastly, increment n in the "CAMPAIGN n" substring
  $data =~ s/(?<=CAMPAIGN )(\d+)/$1 + 1/e;
}

### replace the name of an existing campaign with a new one
sub replace_campaign {
  my ($old_cpn, $new_cpn) = @_;
  $data =~ s/(?<=  "\$\{P\}\/)$old_cpn/$new_cpn/;
}


__DATA__
! List of Campaigns
! -----------------
CAMPAIGN 1
  "${P}/TEST"
  ## widget = uniline
于 2012-04-28T23:09:05.303 回答