如何在perl中正确使用全局变量

时间:2013-04-16 11:05:31

标签: perl

我是perl的新手。我试图通过编写一些程序来理解它。在perl中确定范围让我很难过。

我写了以下内容:

use 5.16.3;
use strict;
use Getopt::Long;

Getopt::Long::Configure(qw(bundling no_getopt_compat));
&ArgParser;
our ($sqluser,$sqlpass);

$sqluser="root";
$sqlpass="mypassword";

sub ArgParser {
    print "Username is ".$sqluser." Password is ".$sqlpass."\n";
    my $crt='';
    my $delete='';
    GetOptions ('create|c=s' => \$crt,
        'delete|d=s' => \$delete
    );
    if ($crt) {
        &DatabaseExec("create",$crt);   
    } elsif ($delete) {
        &DatabaseExec("delete",$delete);    
    } else {
    print "No options chosen\n";
    }
}

sub DatabaseExec {
    use DBI;
    my $dbname=$_[1];
    print "Username is ".$sqluser." Password is ".$sqlpass."\n";
    my $dbh = DBI->connect("dbi:mysql:", $sqluser,$sqlpass);
    my $comand=$_[0];
    if ($_[0] eq "create") {
        my $db_com="create database ".$dbname;
        print 1 == $dbh->do($db_com) ? "Database created\n":"An error occured while creating database. Maybe it exists?\n";
        #print "Executing: ".$db_com."\n";
    } elsif ($_[0] eq "delete") {
        my $db_com="DROP DATABASE ".$dbname;
        #print "Executing: ".$db_com."\n";
        print 1 == $dbh->do($db_com) ? "Database deleted\n":"An error occured while creating database. Maybe it exists?\n";
    }
}

据我所知,我们会将这些声明为主代码和子程序的全局变量。但是,这给出了以下输出:

#~/perlscripts/dbtest.pl -c hellos
Use of uninitialized value $sqluser in concatenation (.) or string at /root/perlscripts/dbtest.pl line 20.
Use of uninitialized value $sqlpass in concatenation (.) or string at /root/perlscripts/dbtest.pl line 20.
Username is  Password is
Use of uninitialized value $sqluser in concatenation (.) or string at /root/perlscripts/dbtest.pl line 44.
Use of uninitialized value $sqlpass in concatenation (.) or string at /root/perlscripts/dbtest.pl line 44.
Username is  Password is
DBI connect('','',...) failed: Access denied for user 'root'@'localhost' (using password: NO) at /root/perlscripts/dbtest.pl line 45.
Can't call method "do" on an undefined value at /root/perlscripts/dbtest.pl line 50.

我不想将这些作为参数传递给sub,而宁愿将它们用作全局变量。有人可以帮我确定我对范围界定的误解吗?

3 个答案:

答案 0 :(得分:11)

调用子例程时,不会声明变量:

&ArgParser;                 # subroutine call
our ($sqluser,$sqlpass);    # declaration

$sqluser="root";            # assignment
$sqlpass="mypassword";

为了在子程序中使用这些全局变量,将子程序放在变量声明之后。

然而,使用全局变量是一件坏事,你应尽可能避免使用它。您可以改为执行此操作,例如:

my $sqluser = "root";
my $sqlpass = "mypass";

ArgParser($sqluser, $sqlpass);    # you should not use & in subroutine calls

然后在子程序中:

sub ArgParser {
    my ($sqluser, $sqlpass) = @_;
    ...

通过这种方式,您的变量可以很好地封装,并且可以避免被意外操作。

关于子程序调用中的&符号&perldoc perlsub中记录了这一点:

To call subroutines:

NAME(LIST);   # & is optional with parentheses.
NAME LIST;    # Parentheses optional if predeclared/imported.
&NAME(LIST);  # Circumvent prototypes.
&NAME;        # Makes current @_ visible to called subroutine.

答案 1 :(得分:5)

Perl没有全局变量。 Perl的含义是:

  • 包变量。
  • Lexically scoped Variables。

包是命名空间。在Perl中,命名空间有时称为。您的默认包名称为main。例如。这完全合法:

use strict;
use warnings;

$main::variable = "What? Where's my 'our' or 'my' declaration?";

print "Look, I can print $main::variable without using 'my' or 'our'!";

我只是用包装前缀我的包变量名称,并且!它们存在!

这让我感到惊愕:

use strict;
use warnings;

$variable = "What? Where's my 'our' or 'my' declaration?";

print "I'm not going to print 'cause you're going to get a compilation error";

使用use strict;,您必须将变量声明为ourmy,或在其前面加上的名称。

包变量最容易理解。包变量实际上存储在Perl变量结构中,因此它们在声明后始终可用:

use strict;
use warnings;

if ( 1 == 1 ) {  #Yes, I know this is always true
    our $foo = "I have a value!";
}

say "Looks like $foo has a value";

词汇范围的变量更难理解。基本上,词法范围的变量在其定义的范围内,但是一旦离开该块就超出范围。它也可以在子块中使用:

use strict;
use warnings;

my $foo = "Foo has a value";

if ( $foo ) {   #Always true
    my $bar = "bar has a value";
    print "$foo\n";    # $foo has a value. This is a sub-block
    print "$bar\n";    # $bar has a value. It was defined in this block
}

print "$foo\n";    # $foo still has a value.
print "$bar\n";    # You'll get en error here. $bar out of scope here

以下是一些建议:

  • 您不需要预先声明子程序。那只是在惹麻烦。
  • 如果您在程序开头定义变量,则可以使用my个变量,它们将在您的子程序中可用,因为它们仍在范围内。
  • 保留&子程序调用。它们会导致子程序工作方式发生细微变化,这些细微变化可能不是你想要的。标准只是调用子程序。
    • 避免? ... : ...,特别是如果您没有使用空格。它使您的程序更难阅读,并且不会节省任何执行时间。
    • 调用子程序后立即将子程序参数拉入变量。
  • Perl为您插入变量。 Perl存在很多问题。它没有真正的面向对象。它不是面向异常的语言。它有很多不妥。其中一个重要优点是您不必经历各种阴谋来打印变量值。当你徘徊在Python粉丝周围时,使用它并骄傲地抬起头。
  • 使用空格使代码更易于阅读。
  • 也许你真正想要的是常量my变量可以使用,但常量可以确保您的程序中不会意外更改这些值。

这是你的代码被重写了。请注意,常量前面没有印记。这些通常不能用字符串插值。但是,如果用@{[...]}包围它们,也可以插入它们。我在下面做了两件事:

use 5.16.3;
use strict;
use Getopt::Long;

use constant {
    SQL_USER => "root",
    SQL_PASS => "mypassword",
};

Getopt::Long::Configure qw(bundling no_getopt_compat);

sub ArgParser {
    print "Username is " SQL_USER . " Password is " . SQL_PASS . "\n";
    my $crt;
    my $delete;
    GetOptions (
        'create|c=s' => \$crt,
        'delete|d=s' => \$delete,
    );
    if ( $crt ) {
        DatabaseExec( "create", $crt );   
    }
    elsif ( $delete ) {
        DatabaseExec( "delete", $delete );    
    }
    else {
        print "No options chosen\n";
    }
}

sub DatabaseExec {
    use DBI;

    my $comand = shift;
    my $dbname = shift;

    print "Username is @{[SQL_USER]} Password is @{[SQL_PASS]}\n";

    my $dbh = DBI->connect(
        "dbi:mysql:",
        SQL_USER,
        SQL_PASS
    );

    if ( $command eq "create" ) {
        my $db_com = "create database $dbname";
        if ( $dbh->do( $db_com ) ) {
            print "Database created\n"
        }
        else {
            print "An error occured while creating database. Maybe it exists?\n";
        }
    } elsif ( $command eq "delete" ) {
        my $db_com = "DROP DATABASE $dbname";
        #print "Executing: ".$db_com."\n";
        if ( $dbh->do($db_com) ) {
            print "Database deleted\n";
        }
        else {
            print "An error occured while creating database. Maybe it exists?\n";
        }
    }
}

答案 2 :(得分:0)

我建议阅读的关于变量作用域的经典资源是Mark-Jason Dominus的Coping with scoping:它描述了Perl变量(包和词汇变量)族的基本分区,并警告了一些不良做法初学者可能会招致。