gpt4 book ai didi

perl - 在 perl 中,这些没有印记的变量是什么?

转载 作者:行者123 更新时间:2023-12-02 06:31:38 24 4
gpt4 key购买 nike

我正在尝试了解高阶 Perl 的平面文件数据库。

在 FlatDB 包中,sub new,第 141 页,他有声明:

bless { FH => $fh, FIELDS =>\@field, FIELDNUM =>\%fieldnum, FIELDSEP => $FIELDSEP } => $class;

其中 $class == FlatDB。

没有印记的这些变量(FH、FIELDNUM 等)是什么?如何打印它们的值、查找它们的类型或使用它们?

FlatDB 似乎是某种散列的散列,但我所有打印值的尝试都导致错误,例如:

printhash(\%fieldnum,"at37:\\%fieldnum=");
# prints the hash properly, BUT
printhash(FlatDB{FIELDNUM),"at38:FlatDB{FIELDNUM}=");
printhash(FlatDB->FIELDNUM,"at39:FlatDB->FIELDNUM=");
# print the error:
# Can't locate object method "FIELDNUM" via package "FlatDB"

为什么它认为 FIELDNUM 是一个方法,当它被定义为一个散列时?

仅供引用:printhash 子是:

sub printhash
{ my $href=shift; # a REFERENCE to a hash
my $msg=shift; # a text message
my %h = %{$href};
my $len = keys %h;;
print "\n$msg, length=$len";
foreach my $k ( keys %h )
{ print "\nkey: $k, value: $h{$k}"; }
print "\n";
}

最佳答案

它们不是变量。

它们是受祝福的哈希引用中的键(即 an object )。 “fat comma ”(=> 运算符)允许将左侧的​​裸词解释为字符串,如果它以字母或下划线开头并且仅包含字母数字字符和下划线。 (这与对象无关,但在初始化散列或散列引用时,或者每当有人明确尝试指示关联时,您通常会看到这种语法。)

回答你的问题:

Why does it think FIELDNUM is a method, when it is defined as a hash?

因为您将它作为一种方法来调用。语法接近 dereference operator ,但不完全一样。事实上,documentation甚至说了这样的话:

Calling a method on an object is written as $object->method.

The left hand side of the method invocation (or arrow) operator is the object (or class name), and the right hand side is the method name.

my $pod = File->new( 'perlobj.pod', $data );
$pod->save();

The -> syntax is also used when dereferencing a reference. It looks like the same operator, but these are two different operations.

和:

"->" is an infix dereference operator, just as it is in C and C++. If the right side is either a [...], {...}, or a (...) subscript, then the left side must be either a hard or symbolic reference to an array, a hash, or a subroutine respectively. (Or technically speaking, a location capable of holding a hard reference, if it's an array or hash reference being used for assignment.) See perlreftut and perlref.

Otherwise, the right side is a method name or a simple scalar variable containing either the method name or a subroutine reference, and the left side must be either an object (a blessed reference) or a class name (that is, a package name). See perlobj.

但实际上,您可能想要的是该类的一个实例,它看起来像这样:

my $obj = FlatDB->new;

然后您可以像这样访问对象成员:

$obj->{FH};
@{$obj->{FIELDS}};
%{$obj->{FIELDNUM}};
$obj->{FIELDSEP};

但是你不应该因为封装。不幸的是,解释该原则和其他 OOP 原则超出了本答案的范围。

关于perl - 在 perl 中,这些没有印记的变量是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34460887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com