Perl

The Perl Bless Function

The object-oriented programming syntax in Perl is a little bit different from the standard object-oriented programming languages like Java, C++, Python, etc. The package keyword is used in Perl to define a class in Perl. The object and method declaration in Perl are similar to the variable and subroutine declaration but the method of declaring an object in Perl to relate the reference and the referent is different from other programming languages. The bless() function is used to do this task. The uses of the bless function to do the object-oriented programming in Perl are shown in this tutorial.

Syntax:

The syntax of the “bless” function is given in the following. This function can be used with one argument or two arguments. Normally, this function is used with two arguments where the first argument is the reference variable and the second argument is the class name that is referenced by the first argument. When it is used with one argument value, the reference variable refers to the current package.

bless ref

or

bless ref, classname

Different Examples of the Bless() Function

The uses of the bless() function in multiple ways are shown in this part of the tutorial.

Example 1: Using the Simple Class and Object

In this example, the package named “Book” contains a subroutine that works like the constructor method of the class. Here, the “bless” function is used to relate the variables with the class name that is provided at the time of calling the Init() method.

#!/usr/bin/perl

use strict;
use warnings;
use 5.34.0;

#Define the package
package Book;
#Define the constructor
sub Init
{
    #Initialize the class name
    my $className = shift;
    #Initialize the variables
    my $variables = {
      'BookName' => shift,
      'AuthorName' => shift,
      'PublishedYear' => shift,
      'Price' => shift
    };

    #Set the the reference with the referent
    bless $variables, $className;
    #Return the reference variable
    return $variables;
}

#Create an object of the class
my $bookObj = Init Book("Learning Perl", "Randal L. Schwartz", 1993, 45);

#Print the values of the class variables
say "Book details:";
say "\nBook Name: $bookObj->{'BookName'}";
say "Author Name: $bookObj->{'AuthorName'}";
say "Published Year: $bookObj->{'PublishedYear'}";
say "Price: \$$bookObj->{'Price'}";

Output:

The following output appears after executing the script:

p1

Example 2: Using the Class and Object with Multiple Methods

In this example, the package named “Products” contains two methods. One method is Init() which is used to initialize the necessary variables and refer to the variables with the class name using the “bless” function. Another method which is calculate_price() is used to calculate the discount price of the product.

#!/usr/bin/perl

use strict;
use warnings;
use 5.34.0;

#Define the package
package Product;
my $variables = {};

#Define the constructor
sub Init
{
    #Initialize the class name
    my $className = shift;
    #Initialize the variables
    $variables = {

      'Id' => shift,
      'Name' => shift,
      'Price' => shift

    };

    #Set the the reference with the referent
    bless $variables, $className;
    #Return the reference variable
    return $variables;
}

#Declare method to calculate discount price
sub calculate_price
{

   my $discount_price = $variables->{'Price'} - $variables->{'Price'}*0.1;
   say "Discount Price: \$$discount_price";

}

#Create an object of the class
my $proObj = Init Product("6745", "Dell monitor", 50);

#Print the values of the class variables
say "Product information after 10\% discount: ";
say "\nId: $proObj->{'Id'}";
say "Name: $proObj->{'Name'}";
say "Original Price: \$$proObj->{'Price'}";

#Call the object method
$proObj->calculate_price();

Output:

The following output appears after executing the script:

p2

Example 3: Using the Class by Creating a Module

In this example, the user-defined Perl module is created in a separate file named “CalPower.pm” where the “bless” function is used. Create this file with the following Perl script. This module calculates the “xn“ where the values of “x” and “n” are provided from the Perl script where this module is imported.

#!/usr/bin/perl

use strict;
use warnings;
use 5.34.0;

#Define the package name
package CalPower;

#Define the constructor
sub Init
{
   my $className = shift;
   my $var =
   {
    number => shift,
    power => shift
   };

   bless $var, $className;
   return $var;

}

#Define the method to calculate the power value
sub Calculate
{
  my $var = shift;
  my $result = $var->{'number'};
  for (my $i = 1; $i < $var->{'power'}; $i++)
{
   $result = $var->{'number'} * $result;
}
return $result;

}

Create a Perl file with the following script where the “CalPower” module is imported to calculate the power based on the input value that is taken from the user.

#!/usr/bin/perl

use strict;
use warnings;
use 5.34.0;
use CalPower;

#Take the base value
print "Enter the value of x:";
chomp(my $x = <>);
#Take the power vale
print "Enter the value of n:";
chomp(my $n = <>);

#Create an object of the class
my $Obj = Init CalPower($x,$n);

#Print the calculated power value
print "$x to the power $n is ";
say $Obj->Calculate();

Output:

The following output appears after executing the script:

p3

Conclusion

The uses of the “bless” function in Perl are shown in this tutorial by creating a package in the same Perl file and creating a module in a different file.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.