in reply to Re: Passing variables to subroutines using Getopt::Long
in thread Passing variables to subroutines using Getopt::Long

Thanks, that works.

I don't see in the docs where position on the command line matters. In fact I thought that was one benefit of Getopt::Long.

  • Comment on Re^2: Passing variables to subroutines using Getopt::Long

Replies are listed 'Best First'.
Re^3: Passing variables to subroutines using Getopt::Long
by GrandFather (Saint) on Mar 21, 2009 at 08:03 UTC

    You are telling Getopt::Long to call the sub fetch to handle the -fetch option. The sub get called at the point that the option is processed. Most likely Getopt::Long processes options in the order they are provided on the command line, although there's no reason to expect the command line options to be processed in any particular order.

    To achieve what you want I'd be inclined to call the sub after Getopt::Long has done its work. Consider:

    use strict; use warnings; use Getopt::Long; my %options; GetOptions(\%options, 'fetch', 'user=s', 'password=s'); if (exists $options{fetch}) { fetch (%options); } sub fetch { my %options = @_; print "$options{password} $options{user}\n"; }

    True laziness is hard work
Re^3: Passing variables to subroutines using Getopt::Long
by Anonymous Monk on Mar 21, 2009 at 08:01 UTC
    Position doesn't matter. You're using a callback to decide your program flow, but you're only supposed to use it to set variables.
    use strict; use warnings; use Getopt::Long; @ARGV = qw( --user user --password pass --fetch bob ); { my $user; my $password; my $fetch; GetOptions( 'fetch' => sub { my( $n, $k, $v ) = @_; print qq~ name = $n key = $k value = undef ~; $fetch = $k ; }, 'user=s' => \$user, 'password=s' => \$password, ); SOMETHING( $user, $password, $fetch ); die "THE END"; } sub SOMETHING { my( $user, $password, $fetch ) = @_; print qq~ user = $user password = $password fetch = $fetch ~; } __END__ $ perl f.pl name = fetch key = 1 value = undef user = user password = pass fetch = 1 THE END at f.pl line 27.