Ano-Tech Computers
Enter keyword:

Perl: Simple algorithm to implement range parameters on command line
Problem:
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
 
Solution:
# 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++;
}

 
Discuss this solution
Did this article solve your problem? Yes No Did not apply

We welcome anyone who is willing to contribute to this public knowledge base, contact siteadmin@atc.no if you have information you would like to share. The idea is not to replace the commercial support sites, but to publish those hard-to-find solutions you've found yourself looking for over and over again.

Show all articles