我正在学习perl并且理解使用shift解包子例程参数是一种常见且公认的做法.我也理解省略函数参数以使用默认@_数组是常见且可接受的做法.
考虑到这两件事,如果你调用一个没有参数的子程序,就@_可以改变can(并且如果使用shift).这是否意味着使用默认参数调用另一个子例程,或者事实上,@_在此之后使用数组,这被认为是不好的做法?考虑这个例子:
sub total { # calculate sum of all arguments
my $running_sum;
# take arguments one by one and sum them together
while (@_) {
$running_sum += shift;
}
$running_sum;
}
sub avg { calculate the mean of given arguments
if (@_ == 0) { return }
my $sum = &total; # gets the correct answer, but changes @_
$sum / @_ # causes division by zero, since @_ is now empty
} …Run Code Online (Sandbox Code Playgroud) 我试图在pSQL表中插入一行,指定键和值作为占位符:
my @keys = keys %db_entr;
my @vals = values %db_entr;
my @items = (@keys, @values);
my $dbh = DBI->connect("DBI:Pg:dbname=testdb;host=localhost", "username", 'password', {'RaiseError' => 1});
my $sth = $dbh->prepare("INSERT INTO grid ( ?, ?, ? ) values ( ?, ?, ? )");
my $rows = $sth->execute(@items);
print "$rows effected\n";
Run Code Online (Sandbox Code Playgroud)
但是,无论我做什么,这都给了我一个错误:
DBD::Pg::st execute failed: ERROR: syntax error at or near "$1"
LINE 1: INSERT INTO grid ( $1, $2, ...
^ at ./file.pl line 262, <STDIN> line 11.
Run Code Online (Sandbox Code Playgroud)
有没有人知道我可能做错了什么?