do some sort of function "-6ren"> do some sort of function "-我在 perl 和 php 中都看到过这个(例如:$variable -> define something),但我以前从未真正使用过它。这个运算符的目的是什么 -> 它是赋值还是传递参数? 谢谢 最-6ren">
gpt4 book ai didi

PHP,Perl,问题。这是什么意思 : "$variable -> do some sort of function "

转载 作者:可可西里 更新时间:2023-11-01 13:43:56 24 4
gpt4 key购买 nike

我在 perl 和 php 中都看到过这个(例如:$variable -> define something),但我以前从未真正使用过它。这个运算符的目的是什么 -> 它是赋值还是传递参数?

谢谢

最佳答案

在 Perl 中,-> 运算符意味着取消引用和调用,具体取决于运算符右侧的内容。如果 rhs 是括号下标 [...],则 {...}(...) 是解引用。如果它是标量 $some_name 或裸词 some_name 则它正在调用方法调用。

my $array_ref = [1, 2, 3];

say $array_ref->[2]; # prints 3
say $$array_ref[2]; # also prints 3

my $hash_ref = {a => 1, b => 2};

say $hash_ref->{b}; # prints 2
say $$hash_ref{b}; # also prints 2

my $code_ref = sub {"[@_]"};

say $code_ref->('hello'); # prints "[hello]"
say &$code_ref('hello'); # also prints "[hello]"

my $object = Some::Package->new();

$object->some_method(...); # calls 'some_method' on $object

my $method = 'foo';

$object->$method(...); # calls the 'foo' method on $object

$object->$code_ref(...); # same as $code_ref->($object, ...)

我个人更喜欢对数组和散列使用双标记形式的取消引用,并且仅将 -> 用于调用代码引用和调用方法。

关于PHP,Perl,问题。这是什么意思 : "$variable -> do some sort of function ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5898550/

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