Open In App

Perl – Attributes in Object Oriented Programming

Improve
Improve
Like Article
Like
Save
Share
Report

In Perl, Object Oriented concept is very much based on references and Arrays/Hashes. The few main terms of object-oriented programming with respect to Perl programming are object, class, and method.

  • In Perl, an object is like a reference to a data type that knows about the class it belongs to. The object is stored as a reference present in the scalar variable. And since scalar only contains a reference to the object, it can even hold different objects present in separate classes.
  • In Perl, a package containing corresponding methods which are required to create and manipulate objects is known as a class.
  • In Perl, the method is a subroutine that is defined within the package. A package name or an object reference is the first argument to the method depending on whether the method affects the current class or object.

Attributes

Attributes can be defined by each class. When we represent them as objects, we assign values to those attributes. For eg, even every ‘file’ object has a path. Attributes are also known as properties.

Attributes are typically defined as read-only or read-write. Read-only attributes can be set only when the object is created, while read-write attributes can be altered at any time. The value of an attribute can itself be another object. And it’s not necessary for every class to have attributes and methods.

Perl has no special syntax for attributes. In the back, attributes are often stored as keys in the object’s underlying hash.

Perl




sub new{
    my ($class, $args) = @_;
    my $self = bless { serial => $args->{serial},
                       name => $args->{name},
                       price => $args->{price}
                     }, $class;
}


Whenever we call the new() method, Perl automatically passes the class name as the first argument to the special array @_.
When we create an object, we actually create a reference that knows about the class it belongs to. Bless (which is a built-in function) is used to bless the reference to the class and then return an instance of the class. In the above example, we have passed a hash reference to the bless() function. But one can pass any kind of reference to the bless function e.g., array reference, which makes it much easier to work with a hash reference.

Creating default attribute values

Now we can know how to apply attributes. But what will happen if we don’t pass all the arguments in our Perl program? In this case, the attributes will be initialized as ‘null’ by the object. Hence there is a way to avoid that by setting default values that are overridden if the argument is present when the object is constructed. Logical or operator || can be used to achieve this effect.

Perl




sub new{
sub new{
    my ($class, $args) = @_;
    my $self = {
                    name => $args->{name} || ‘iPhone XR’,
                    price => $args->{price} || ‘52K’,
               },
    Return bless $self, $class;
}
1;


Accessing attributes

The best way to accessing attributes is via accessor methods. These are methods that help us in Perl to get or set the value of each attribute. 

The two types of accessor are: 

  • Getter: It gets the attribute’s value.
  • Setter(also known as Mutator): It sets the attributes value.

Getter_and_setter

Perl




package Person;
use strict;
use warnings;
sub new {
    my ($class, %args) = @_;
   
    my $self = \%args;
   
    bless $self, $class;
   
    return $self;
}
   
sub name {
    my ($self, $value) = @_;
    if (@_ == 2)
    {
        $self->{name} = $value;
    }
    return $self->{name};
}
1;
 
# Assigning the object 'Person'
# to the $teacher variable.
my $teacher = Person->new;
 
# Setting the attribute 'name'
# to the variable '$teacher'
$teacher->name('Foo');
 
printf $teacher->name;


Output:

Foo

We are calling the constructor here Person->new, which returns an object we assign to $teacher and then we are calling the accessor $teacher->name(‘Foo’) using it as a setter by providing it a value and then using the same accessor as a getter $teacher->name (without passing a value) making it fetch the current value of the attribute while using the same method called ‘name’. 
When we call the $teacher->name(‘Foo’), Perl will notice that $teacher is a blessed reference to a hash and it was blessed into the Person (name-space). If there wasn’t a blessed reference, it wouldn’t have known what to do with the arrow and the “name” after that and it would’ve throw an exception: (Can’t call method .. on unblessed reference)

Well since it is blessed into the Person name-space, Perl will start to look for the “name” function in the Person name-space and once that function is found, Perl will call that function with the parameters which we’ve passed onto it, but it will also take the variable we had on the left-hand side of the arrow and pass it as the first argument. ($teacher in our case) .
In our example this “name” function is once called as a “setter” when we pass a value to it, and once as “getter” when we don’t pass any value through it. Because Perl passes the object as the first parameter this means that when it is called a “setter” we are actually going to get 2 parameters and when it is called a “getter” we are going to get one parameter.
The first statement in the “name” subroutine assigns the parameters to local variables. In the second statement now, Perl checks whether the function should act as a getter or as a setter? Perl checks the number of parameters. If it gets two parameters then this is a setter. In this case, it takes the content of $self.
If we use the ‘name’ function as a ‘getter’, then we don’t pass any value to it, which means $value will be undefined, but more importantly @_ will only have one element. This it will skip the assignment and the only thing it’ll do is to return the value of the ‘name’ key from the hash reference.

Conclusion: 
This shows that the attributes of an object in Perl are just key/value pairs in a hash reference.
In the above example, we can see that the setter/getter is just a plain Perl function.
Therefore it also implements that the attributes of an object are simple entries in the HASH reference representing the object. The key in the hash is the name of the attribute and the respective value in the HASH is the value of the attribute.
 



Last Updated : 03 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads