开发者

How do you parse simple command line options with Perl?

When i run a Perl file with command line input it should update a field in the table.

For example

开发者_Python百科perl function_impl.pl --address_only

if it receives the input parameter --address_only then t should update only address field in the db of that Perl script.How to implement this.


Getopt::Long is a very common and very easy way in Perl to parse command line parameters.

my %args = ();
GetOptions (\%args, 'address_only');       # will store true value in $args{address_only}

if ($args{address_only}) {
    # Update address
}

Please show us the code you use to update the table so we can provide assistance with that part if you need it.

Also, how will you supply the update value? From your example you won't be supplying it via command line, so I assume it's hard-coded? If you want to supply on command line, change the above code to accept values for the parameter:

my %args = ();
GetOptions (\%args, 'address_only=s'); # will store address value in $args{address_only}
# Usage: function_impl.pl --address_only joe@myaddress.com

As a trivial example, you can build "SET" part of update statement:

my $set_fields = 0;
if ($args{address_only}) {
    $set_fields .= ", " if $set_fields; # comma separate if >1 set
    $set_fields .= qq[address = "$args{address_only}"];
    # or $set_fields .= qq[address = "$hardcoded_address"];
}
# Build the full UPDATE SQL statement using $set_fields
# Execute SQL statement


If your script accepts zero or one argument you can do:

if( $#ARGV == 0 ) {     # one argument passed
        if($ARGV[0] eq '--address_only') {
                # --address_only passed
        } else {
                # something else passed
        }
}elsif( $#ARGV == -1 ) { # no argument passed

}else{                   # more than one arg passed

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜