package opts;

=head1 NAME

perl - Subroutines to parse arguments to a program

=head1 SYNOPSIS

   use opts;
   $bool = &opts::getopt("-v");     # $bool is true if -v was passed, false otherwise
   $arg = &opts::getoptwarg("-P");  # $arg is arg after -P if -P was passed, "" otherwise
   &opts::ignoreopts;               # ignore any more args that start with "-"

=head1 DESCRIPTION

These routines parse the arguments to perl program.  The first just tells
whether or not a simple argument was passed, and removes it from $ARGS if
it was.  The second retrieves an argument to the option asked for.  It returns
"" if the option does not exist or if there is no argument following it.  Finally,
the last routine ignores and removes any more arguments starting with "-".

=cut

# Synopsis: if (getopt("-v")) { ... }
sub getopt
{
   local(@args);
   @args = grep /^$_[0]$/, @ARGV;
   if (@args)
   {  @ARGV = grep ! /^$_[0]$/, @ARGV;
      1;
   }
   else
   {  0;
   }
}


# Get opt with an argument
# Synopsis: $arg = getopt("-P"); if ($arg) { ... }
sub getoptwarg
{
   local(@args, @tmp);
   $rv = "";

   @tmp = grep /^$_[0]/, @ARGV;
   if (@tmp)
   {
      for($i = 0; $i < @ARGV; ++$i)
      {
         $_ = $ARGV[$i];
         if (! $rv && /^$_[0]/)
         {
            if (/^$_[0]$/)
            {
               ++$i;
               $rv = $ARGV[$i];
            }
            else
            {  $_ = substr($_, length $_[0]);
               $rv = $_;
            }
         }
         else
         {  push(@args, $_);
         }
      }

      @ARGV = @args;
   }

   return $rv;
}


# If there are any more arguments starting with "-", strip them
sub ignoreopts
{
   local(@args);
   @args = grep ! /^-/, @ARGV;
   @ARGV = @args;
}

1;
