Advertisement
andrewb

parseArgs.pl

Aug 8th, 2014
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.18 KB | None | 0 0
  1. #!/usr/bin/perl -w
  2. ##########
  3. # A couple of cool subroutines for parsing command line arguments.
  4. # It's been done a thousand, thousand times but this is the first time I did it right.
  5. ##########
  6. use Data::Dumper;
  7. use strict;
  8. use warnings;
  9.  
  10. sub splitArg {
  11.     my $str = shift;
  12.     return split(/=/, $str);
  13. }
  14.  
  15. sub parseArgs {
  16.     my %args = ();
  17.     my $lastarg = "";
  18.     foreach my $arg (@ARGV) {
  19.         if (substr($arg, 0, 2) eq "--") {
  20.             my $temp = substr($arg, 2);
  21.             if ($arg !~ m/=/) {
  22.                 $lastarg = $temp;
  23.             } else {
  24.                 my ($k, $v) = splitArg($temp);
  25.                 $args{$k} = $v;
  26.             }
  27.         }
  28.         elsif (substr($arg, 0, 1) eq "-") {
  29.             my $temp = substr($arg, 1);
  30.             if ($arg !~ m/=/) {
  31.                 $lastarg = $temp;
  32.             } else {
  33.                 my ($k, $v) = splitArg($temp);
  34.                 $args{$k} = $v;
  35.             }
  36.         }
  37.         else {
  38.             if (length($lastarg) > 0) {
  39.                 $args{$lastarg} = $arg;
  40.                 $lastarg = "";
  41.             }
  42.         }
  43.     }
  44.     return %args;
  45. }
  46.  
  47. my %args = parseArgs();
  48.  
  49. print Dumper(%args);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement