Forums.ATC.no

Teknisk => Generelt teknisk => Emne startet av: ATC på 27. ſeptember 2008, 18:24 pm

Tittel: Perl: Simple algorithm to implement range parameters on command line
Skrevet av: ATC27. ſeptember 2008, 18:24 pm
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
Tittel: [Solved] Perl: Simple algorithm to implement range parameters on command line
Skrevet av: ATC27. ſeptember 2008, 18:24 pm
# 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++;
}