你如何用Perl解析简单的命令行选项?

时间:2010-12-10 11:38:02

标签: perl

当我使用命令行输入运行Perl文件时,它应该更新表中的字段。

例如

perl function_impl.pl --address_only

如果收到输入参数--address_only,那么t应该只更新该Perl脚本的db中的地址字段。如何实现它。

2 个答案:

答案 0 :(得分:11)

Getopt::Long是Perl解析命令行参数的一种非常常见且非常简单的方法。

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

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

请向我们展示您用于更新表格的代码,以便我们在您需要时提供该部分的帮助。

另外,您将如何提供更新值?从你的例子中你不会通过命令行提供它,所以我认为它是硬编码的?如果要在命令行上提供,请更改上面的代码以接受参数的值:

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

作为一个简单的例子,您可以构建更新语句的“SET”部分:

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

答案 1 :(得分:-4)

如果你的脚本接受零或一个参数,你可以这样做:

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

}
相关问题