在Perl中,如何传递数字范围(例如:100到200)作为命令行参数?

时间:2019-01-23 11:49:02

标签: perl command-line-arguments

我有一个使用命令行参数的Perl程序。我想将100到200的数字作为一个参数传递。由于很难给出所有介于100和200之间的数字,因此是否可以在命令行参数中使用范围运算符?

./my_program --target 100..200

2 个答案:

答案 0 :(得分:2)

怎么样?

#!/usr/bin/perl
use strict;
use warnings;

use Getopt::Long;

my %options;
GetOptions(\%options, (
           'target=s',
       ))
    or die "$!\n";

die "option --target is missing!\n"
    unless exists $options{target};

my @list;
if (my($number) = ($options{target} =~ /^(\d+)$/)) {
    push(@list, $number);
} elsif (my($start, $end) = ($options{target} =~ /^(\d+)\.\.(\d+)$/)) {
    if ($start < $end) {
        push(@list, $start..$end);
    } else {
        push(@list, reverse($end..$start));
    }
} elsif (my($first, $others) = ($options{target} =~ /^(\d+)[\s,]((?:\d+[\s,])*\d+)$/)) {
    push(@list, $first, split(/[\s,]/, $others));
} else {
    die "invalid argument for --target option: $options{target}\n";
}

for my $target (@list) {
    print "${target}\n";
}

exit 0;

示例运行:

$ perl dummy.pl --target 1234
1234

$ perl dummy.pl --target 1,4,5,40,17,30
1
4
5
40
17
30

$ perl dummy.pl --target "1 4,5 40 17,30"
1
4
5
40
17
30

$ perl dummy.pl --target 4..10
4
5
6
7
8
9
10

$ perl dummy.pl --target 10..4
10
9
8
7
6
5
4

答案 1 :(得分:2)

Set::IntSpan处理繁琐的解析范围:

#!/usr/bin/env perl

use strict;
use warnings;
use 5.010;

use Getopt::Long;
use Set::IntSpan;

GetOptions( 'target=s' => \( my $target ) );

my $set = Set::IntSpan->new( $target );

while( my $item = $set->next ) {
    say $item;
}

具有以下结果:

% perl myprogram.pl  --target 1-10,12-15
1
2
3
4
5
6
7
8
9
10
12
13
14
15