Structs in Perl

Structs in Perl

Perl does not have a built-in struct type, but we can achieve similar functionality using packages and hash references. Here’s how you can define a person structure and use it in Perl.

Defining the Person Structure

In Perl, we use packages to define a class, and create objects as hash references.

package Person;

sub new {
    my ($class, $name, $age) = @_;
    my $self = {
        name => $name,
        age  => $age,
    };
    bless $self, $class;
    return $self;
}

sub set_age {
    my ($self, $age) = @_;
    $self->{age} = $age;
}

sub get_name {
    my $self = shift;
    return $self->{name};
}

sub get_age {
    my $self = shift;
    return $self->{age};
}
1;

Creating and Using the Person Object

Now let’s see how we can use this Person package to create and manipulate person objects.

use strict;
use warnings;
use Person;

# Creating a new person object
my $bob = Person->new("Bob", 20);
print "Person: " . $bob->{name} . ", " . $bob->{age} . "\n";

# Creating another person object with named fields
my $alice = Person->new("Alice", 30);
print "Person: " . $alice->{name} . ", " . $alice->{age} . "\n";

# Creating a person with omitted age field, will default to `undef`
my $fred = Person->new("Fred");
print "Person: " . $fred->{name} . ", " . (defined $fred->{age} ? $fred->{age} : "undefined") . "\n";

# Getting a pointer (reference) to the person object
my $ann = Person->new("Ann", 40);
print "Pointer to Person: " . ${$ann}{name} . ", " . ${$ann}{age} . "\n";

# Using a constructor function
sub new_person {
    my ($name) = @_;
    my $person = Person->new($name);
    $person->set_age(42);
    return $person;
}
my $jon = new_person("Jon");
print "Person: " . $jon->{name} . ", " . $jon->{age} . "\n";

# Accessing struct fields with a dot equivalent
my $sean = Person->new("Sean", 50);
print "Name: " . $sean->get_name() . "\n";
print "Age: " . $sean->get_age() . "\n";

# Create a reference to the object and dereference it
my $sp = $sean;
print "Age from reference: " . $sp->get_age() . "\n";

# Modifying the structure fields
$sp->set_age(51);
print "Modified age: " . $sp->get_age() . "\n";

# Anonymous structure
my $dog = {
    name   => "Rex",
    isGood => 1,
};
print "Dog: " . $dog->{name} . ", " . $dog->{isGood} . "\n";

To run the program, save the Person package in a file called Person.pm, and the main script code in another file, such as structs.pl. Then you can execute it using:

$ perl structs.pl
Person: Bob, 20
Person: Alice, 30
Person: Fred, undefined
Pointer to Person: Ann, 40
Person: Jon, 42
Name: Sean
Age: 50
Age from reference: 50
Modified age: 51
Dog: Rex, 1

In this example, we learned how to create and manipulate structures using Perl’s OOP capabilities. Next, let’s dive into other features of Perl!