Skrevet av Emne: Perl: Simple algorithm to implement range parameters on command line  (Lest 4241 ganger)

ATC

  • Gjest
  • [applaud]0
  • [smite]0
  • A script accepts multiple numbers as parameters, like this:
    ./process 1 2 3

    How to make it possible to specify ranges like this:
    ./process 1 - 10 25 - 100



    ATC

    • Gjest
  • [applaud]0
  • [smite]0
  • # Scan the argument array for the '-' character and splice it

    my $index = 0;
    foreach my $arg (@ARGV) {
      if ($arg eq "-") {
        if ($index > 0 && $index < scalar $#ARGV) {
          my $from = $ARGV[$index-1];
          my $to   = $ARGV[$index+1];
          splice(@ARGV, $index-1, 3, ($from .. $to)); # Perl magic
        } else {
          splice(@ARGV, $index, 1);
          warn "Warning: Incorrect use of range specifier '-'\n";
        }
      }
      $index++;
    }