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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With