On 7/5/07, Ray <[EMAIL PROTECTED]> wrote:

I want to try to construct
the arguments for GetOptions, but in a dynamic way. So, instead of
hard-coding my switches, like this:
GetOptions (
       showlog       => \$MyArgs{showlog},
       'strategy=s'  => \$MyArgs{strategy}
)

like is shown in the GetOptions documentation page, I would like to
feed the list based upon some arrays

That should be possible. If you assemble an argument list that looks
just like a valid argument list for GetOptions, it will behave just as
if you had hard-coded that same argument list.

How would I set $target_hash_ref to support say the "showlog" switch, and
the "strategy" option? Would I be able to refer to each option such as
$target_hash_ref{showlog}, or $target_hash_ref{strategy} ?

The idea of having a target hash is so that all of the options show up
there, in one place, instead of being scattered among many variables.
That's vital for your application, since you can't know all the names
ahead of time anyway. But you can get $target_hash_ref from wherever
you can get a reference to your target hash:

 my %h;  # New, empty hash for all options.
 my $target_hash_ref = \%h;

Or, if you were writing a subroutine that is merely given a hash
reference as a parameter, you could use that parameter to get
$target_hash_ref.

To go the other direction, and get a value from it, you need to
dereference it. The easiest way to access a single element is with the
small arrow:

 if ($target_hash_ref->{"showlog"}) {
   print LOG "Captain's log, stardate $now. Sensors report that the\n";
   print LOG "mysterious 'showlog' feature has been activated!\n";
 }

If you need the whole hash, it's available as well:

 my @all_opt_names = sort keys %$target_hash_ref;
 print "All identified options: @all_opt_names\n";

If an option has been configured to return an array or hash reference,
you'll need one more step of dereferencing to pull out an element. Or
you can use the curly-brace notation to dereference the entire
variable.

 my $first_color = $h{"colors"}->[0];
 my @colors = @{$h{"colors"}};  # specified as 'colors=s@'

You may have noticed that the last example switched back to the "real"
name of the hash, %h. Because there's no reference being dereferenced
before it's time to look up the hash key, there's no arrow between the
'h' and the '{' around the key. Of course, accessing that hash by %h
or $target_hash_ref gives the same data, because it's the same hash
either way.

See the perlref manpage for more information on references and how to
dereference them.

Cheers!

--Tom Phoenix
Stonehenge Perl Training

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


Reply via email to