简体   繁体   中英

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 -xyz -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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM