- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating and Using Objects using Perl
To create an instance of a class (an object) we need an object constructor in Perl. This constructor in Perl is a method defined within the package. Most programmers choose to name this object constructor method new, but in Perl you can use any name.
You can use any kind of Perl variable as an object in Perl. Most Perl programmers choose either references to arrays or hashes.
Let's create our constructor for our Person class using a Perl hash reference. When creating an object, you need to supply a constructor, which is a subroutine within a package that returns an object reference. The object reference is created by blessing a reference to the package's class. For example −
package Person; sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; # Print all the values just for clarification. print "First Name is $self->{_firstName}\n"; print "Last Name is $self->{_lastName}\n"; print "SSN is $self->{_ssn}\n"; bless $self, $class; return $self; }
Now Let us see how to create an Object.
$object = new Person( "Mohammad", "Saleem", 23234345);
You can use simple hash in your consturctor if you don't want to assign any value to any class variable. For example −
package Person; sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; }
- Related Articles
- Creating Variables in Perl
- Creating Hashes in Perl
- Creating and using packages in Java
- Creating and Using a MySQL Database
- Hello World using Perl.
- Creating Arrays using Javascript
- Creating Dictionary using Javascript
- First CGI Program using Perl
- Using GET Methods in Perl
- Using POST Methods in Perl
- Creating Variables using Pre Request Script using Postman?
- Creating Animated Counter using HTML, CSS, and JavaScript
- Creating a Set using Javascript
- Creating a BinaryTree using Javascript
- Creating 3D animation using matplotlib
