What is the arrow operator in Perl 5.34?

The arrow operator (->) is an infixThese operators come between their operands operator that dereferences a variable or a method from an object or a class.

The operator has associativity that runs from left to right. This means that the operation is executed from left to right.

Use

The right-hand side of the operator may be an array subscript ([...]), a hash subscript ({...}), or a subroutine argument ((...)). In such cases, the left-hand side must reference an array, a hash, or a subroutine, respectively.

For example:

$arr->[7] # an array dereference 

$hash->{"something"} # a hash dereference 

$subroutine->(1,2) # a subroutine dereference

The left-hand side of the operator may also reference an object or a class name. In such cases, the right-hand side of the operator corresponds to the method that we want to invoke or the variable we wish to access.

For example:

$harry = Wizard->new("Harry Potter"); # a class method call 

$harry->spell($Expelliarmus); # an object method call 
Left and right hand sides of the arrow operator

Code

use strict;
use warnings;
# reference to array
my $arr = [2, 3, 5, 7, 11];
# reference to hash
my $hash = {'a' => 1,'b' => 2};
# using arrow operator
print "$arr->[3]\n"; # print 4th element of arr
print "$hash->{'a'}\n"; # print value of key 'a'

In the above example, we define an array and a hashmap. We access specific values within them using the -> operator.

package Wizard;
# constructor
sub new
{
my $class_name = shift;
my $self = {
'FirstName' => shift,
'LastName' => shift
};
# Using bless function
bless $self, $class_name;
return $self;
}
sub spell
{
print "Casting spell...EXPELLIARMUS\n";
}
my $harry = Wizard->new("Harry","Potter");
# Accessing variables using ->
print "$harry->{'FirstName'}\n";
print "$harry->{'LastName'}\n";
# Method call using ->
$harry->spell

In this example, we define a class Wizard. Using ->, we invoke the constructor (new) to create a Wizard object.

The bless() function associates the $self object with the class Wizard.

Next, the -> operator invokes the spell method of the Wizard class.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved