我是 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.
我不想将它们作为参数传递给子进程,而宁愿将它们用作全局变量。有人可以帮助我确定我对范围界定的误解吗?
调用子例程时未声明变量:
&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 http://perldoc.perl.org/perlsub.html:
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)