Hello Jakob,

> I'm trying to create a script with where you can put a flag to the script
or
> not
> fx run it like:
> 
> script -h
> or just
> script

I would use one of the Getopt::* modules, because parsing command line
options is something very standard, and as you add more and more options,
the complexity of your script will grow exponentially. It's better to accept
a bit more complexity now, instead of plowing through lots of added
complexity later...

> if ( $ARGV[0] =~ /-h/ ) {

The error is that if you start the script without any options, $ARGV[0] is
undefined. I would do it like this :

# By default, the special ability is off.
my $special_ability_enabled = 0;

foreach my $arg (@ARGV) {
    if ($arg =~ /^-h$/) {
        # Enable the special ability!
        # or if -h just prints a help message, print it here.
        $special_ability_enabled = 1;
    }
}

That loop will not be entered if there were no command line arguments (which
is good, it will get rid of your error), and it also has the added benefit
of checking all the command line argument for a match, instead of just the
first one. So both these commands will enable the special ability (whereas
just checking $ARGV[0] would have only worked for the first one) :

<your_script> -h
<your_script> <input_file> -a -h

In addition, note that I changed the regex you use to check the command line
option a bit. If you still want to try to parse command line options
yourself, your regex would match the following :

-h
-help (not too bad so far)
-hello (huh?)
-hogwash
robert-henri (ok, this is not good)
set-new-hash-value

Therefore, I used /^-h$/ so that it will only match if '-h' is the only
thing in the string. If you want to match anything that starts with '-h' too
(like -help), you could remove the '$'.


Having said this, I still strongly recommend using a module to do the nitty
gritty work of parsing the arguments for you. One of them (Getopt::Std,
Getopt::Long or both) almost always comes with Perl, so you shouldn't even
have to install one from CPAN or PPM...

Good luck,

J-S

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to