in reply to Optional Arguments..?
The array, @ARGV contains the various arguments passed on the command line. To access the first element by index, it would be $ARGV[0]. You're using that first element to handle the command line switch, L, U or D. The second arg is $ARGV[1], and that's where you're passing the key. The third (optional) parameter is $ARGV[2]. That element will either have a value, or it will be undefined. To detect which, you might do something like this:
if( defined $ARGV[2] ) { # Handle the search string. } else { # Perform whatever default preparations are necessary in # the absence of a defined search string. }
So the key is to test $ARGV[2] for definedness. There are a couple of useful ways to do that. The most common by far is the defined built-in function. But there's also the // and //= operators, described in perlop. With //=, you could do something like this:
$ARGV[2] //= 'Default value';
In this case, if $ARGV[2] already contains a value, the line has no effect. If it doesn't contain a value, '<c>Default value' is assigned.
Using the // operator might look like this:
my $pattern = $ARGV[2] // 'Default value';
Here, $pattern receives the contents of $ARGV[2] if $ARGV[2] is defined. If it's undefined, then 'Default value' is assigned to $pattern.
The // and //= operators were introduced to Perl in version 5.10.0 (I think). So they won't work if you're stuck using older versions. defined works all the way back to the earliest Perl 5 versions, and possibly more.
Welcome to Perl! :)
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Optional Arguments..?
by Watergun (Novice) on Jun 03, 2012 at 03:52 UTC | |
by davido (Cardinal) on Jun 03, 2012 at 07:18 UTC | |
by Watergun (Novice) on Jun 03, 2012 at 08:28 UTC | |
by davido (Cardinal) on Jun 03, 2012 at 08:53 UTC |