无法理解为什么函数login all返回的值与传递给它的内容不对应.
以下是我的代码片段
package This_package;
.......
# returned from function that parses post data ($reqparam)
my $thisuser = $$reqparam{"username"};
# escape '@', username is an email
$thisuser =~ s/@/\@/;
my $thisuser_pass = $$reqparam{'password'};
print $thisuser; # ok
print $thisuser_pass; # ok
my $obj = new users;
my $valid_user = $obj->login($thisuser, $thisuser_pass);
.......
package Another_package;
sub new {
my ($class) = @_;
my $self = {
_login => undef,
_create_user => undef,
....
};
bless $self, $class;
return $self;
}
sub login ($$){
my ($user, $pass) = @_;
# some processing
.....
return $user; # prints users=HASH(...)
# return $pass; # prints the value of $user (the actual value)
# instead of the value of $pass
}
Run Code Online (Sandbox Code Playgroud)
尝试通过将一些代码从php转换为perl来学习perl.我遇到了这个问题,我尝试了一些替代方案,但显然有一些我没有得到的东西!
当你调用像这样的函数时
my $valid_user = $obj->login($thisuser, $thisuser_pass);
Run Code Online (Sandbox Code Playgroud)
第一个参数通常是这样做的
sub login
{
my ( $self , $user , $password ) = @_;
}
Run Code Online (Sandbox Code Playgroud)
你错过了$ self
因为您缺少$ self,所以您的用户实际上是对象,而您的密码实际上是用户.
如果你来自另一种被反对的语言,如C++,Java或C#,这 是一个perl gotcha(没有双关语:)).另一个是,即使从一个对象方法,如果你想调用另一个成员方法,你必须使用self
$self->callAnotherObject( $user );
Run Code Online (Sandbox Code Playgroud)
只是打电话不会
callAnotherObject( $user );
Run Code Online (Sandbox Code Playgroud)
当您使用面向对象的syntax($obj->login($thisuser, $thisuser_pass))来调用子例程时,第一个参数将是对象本身.您应该说,您通常会看到面向对象的模块使用如下语法:
sub login {
my ($self, $user, $pass) = @_;
...
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你不应该没有($$)充分的理由使用prototypes().Perl中的原型的使用方式与其他语言中的原型不同,在任何情况下,当您使用间接语法调用子例程时,都会忽略原型(幸运的是,在您的情况下,因为您实际上是使用3个参数调用它).