Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php, perl, question. what does this mean: " $variable -> do some sort of function "

I have seen this (example: $variable -> define something) in both perl and php but I never really used it before. What is the purpose of this operator -> Does it assign a value or pass a param?

Thanks

like image 879
tdjfdjdj Avatar asked May 05 '11 13:05

tdjfdjdj


1 Answers

In Perl, the -> operator means both dereference and invoke, depending on what is to the right of the operator. If the rhs is a bracketed subscript [...], {...}, or (...) is a dereference. If it is a scalar $some_name or a bareword some_name it is invoking a method call.

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, ...)

I personally prefer to use the doubled sigil form of dereferencing for arrays and hashes, and use the -> only for calling code references and for calling methods.

like image 196
Eric Strom Avatar answered Sep 23 '22 23:09

Eric Strom