[英]Perl dereferencing a subroutine
I have come across code with the following syntax: 我遇到了具有以下语法的代码:
$a -> mysub($b);
And after looking into it I am still struggling to figure out what it means. 在研究之后,我仍在努力找出含义。 Any help would be greatly appreciated, thanks! 任何帮助将不胜感激,谢谢!
What you have encountered is object oriented perl. 您遇到的是面向对象的perl。
it's documented in perlobj
. 它记录在perlobj
。 The principle is fairly simple though - an object is a sort of super-hash, which as well as data, also includes built in code. 其原理很简单,但-一个对象是一种超的哈希, 其除了数据外,还包括内置的代码。
The advantage of this, is that your data structure 'knows what to do' with it's contents. 这样做的好处是,您的数据结构“知道如何处理”其内容。 At a basic level, that's just validate data - so you can make a hash that rejects "incorrect" input. 从根本上讲,这只是验证数据-因此您可以进行哈希处理以拒绝“不正确”的输入。
But it allows you to do considerably more complicated things. 但是,它可以使您做得多得多的事情。 The real point of it is encapsulation, such that I can write a module, and you can make use of it without really having to care what's going on inside it - only the mechanisms for driving it. 它的真正目的是封装,这样我就可以编写一个模块,并且您可以使用它而不必真正关心它内部发生了什么—只是驱动它的机制。
So a really basic example might look like this: 因此,一个非常基本的示例可能如下所示:
#!/usr/bin/env perl
use strict;
use warnings;
package MyObject;
#define new object
sub new {
my ($class) = @_;
my $self = {};
$self->{count} = 0;
bless( $self, $class );
return $self;
}
#method within the object
sub mysub {
my ( $self, $new_count ) = @_;
$self->{count} += $new_count;
print "Internal counter: ", $self->{count}, "\n";
}
package main;
#create a new instance of `MyObject`.
my $obj = MyObject->new();
#call the method,
$obj->mysub(10);
$obj->mysub(10);
We define "class" which is a description of how the object 'works'. 我们定义“类”,它描述对象“工作”的方式。 In this, class, we set up a subroutine called mysub
- but because it's a class, we refer to it as a "method" - that is, a subroutine that is specifically tied to an object. 在这个类中,我们建立了一个名为mysub
的子例程-但由于它是一个类,因此将其称为“方法”-即专门与对象绑定的子例程。
We create a new instance of the object (basically the same as my %newhash
) and then call the methods within it. 我们创建对象的新实例(基本上与my %newhash
相同),然后在其中调用方法。 If you create multiple objects, they each hold their own internal state, just the same as it would if you created separate hashes. 如果创建多个对象,则它们每个都拥有自己的内部状态,与创建单独的散列时的状态相同。
Also: Don't use $a
and $b
as variable names. 另外:不要使用$a
和$b
作为变量名。 It's dirty. 这个不干净。 Both because single var names are wrong, but also because these two in particular are used for sort
. 既因为单个var名称错误,又因为这两个特别用于sort
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.