开发者

How can I modify complex command-line argument strings in Perl?

I have a command line that I'm trying to modify to remove some of the arguments. What makes this complex is that I can have nested arguments.

Say that I have this:

$cmdline = "-a -xyz -a- -b -xyz -b- -a -xyz -a-"

I have three different -xyz flags that are to be interpreted in two different contexts. One is the -a context and the other is the -b context.

I want to remove the "a" -xyz's but leave the ones in the "b" -xyz.

in the above case, I want:

-a -a- -b -xyz -b- -a -a-

Alternately, if I have:

-a -123 -a- -b -xyz -b- -a -xyz -a-"

I want:

-a -123 -a- -a -xyz -a- -b -x开发者_开发问答yz -b- -a -a-

It's this second case that I'm stuck on.

How can I most effectively do this in Perl?


use strict;
use warnings;

my @cmds = (
    '-a -123 -a- -b -xyz -b- -a -xyz -a-',
    '-a -xyz -a- -b -xyz -b- -a -xyz -a-',
);

for my $c (@cmds){
    # Split command into parts like this: "-a ... -a-"
    my @parts = $c =~ /( -\w\s .+? -\w- )/gx;
    for my $p (@parts){
        $p =~ s{-xyz\s+}{} if $p =~ /^-a/;
    }
    # The edited command line consists of the joined parts.
    print "@parts\n";
}


#!/usr/bin/perl -w
sub replace_in_ctx {
  my $cmdline = shift;
  my @result = ();
  for (split / /, $cmdline) {
    push @result, $_ unless /-a/../-a-/ and /^-xyz$/;
  }
  return join " ", @result;
}
# first case
print replace_in_ctx("-a -xyz -a- -b -xyz -b- -a -xyz -a-") . "\n";

# second case
$_ = replace_in_ctx("-a -123 -a- -b -xyz -b- -a -xyz -a-");
s/-a -123 -a-/$& -a -xyz -a-/;
print "$_\n";

Run it:

$ perl match_context.pl 
-a  -a- -b -xyz -b- -a  -a-
-a -123 -a- -a -xyz -a- -b -xyz -b- -a  -a-


If I understand correctly, a context begins with -a and ends with -a-.

use warnings; use strict;

my $cmdline = "-a -123 -a- -b -xyz -b- -a -xyz -a-";
$cmdline =~ s/( ?-a) +-xyz +(-a- ?)/$1 $2/g;

print "$cmdline\n";
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜