Using Classes as Structs
Problem
You’re used to structured data types more complex than Perl’s arrays and hashes, such as C’s structs and Pascal’s records. You’ve heard that Perl’s classes are comparable, but you aren’t an object-oriented programmer.
Solution
Use the standard Class::Struct module to declare C-like structures:
use Class::Struct; # load struct-building module struct Person => { # create a definition for a "Person" name => '$', # name field is a scalar age => '$', # age field is also a scalar peers => '@', # but peers field is an array (reference) }; my $p = Person->new(); # allocate an empty Person struct $p->name("Jason Smythe"); # set its name field $p->age(13); # set its age field $p->peers( ["Wilbur", "Ralph", "Fred" ] ); # set its peers field # or this way: @{$p->peers} = ("Wilbur", "Ralph", "Fred"); # fetch various values, including the zeroth friend printf "At age %d, %s's first friend is %s.\n", $p->age, $p->name, $p->peers(0);
Discussion
The
Class::Struct::struct
function builds struct-like
classes on the fly. It creates a class of the name given in the first
argument, and gives the class a constructor named
new
and per-field accessor methods.
In the structure layout definition, the keys are the names of the
fields and the values are the data type. This type can be one of the
three base types, '$'
for scalars,
'@'
for arrays, and
'%'
for hashes. Each accessor method can be called without arguments to fetch the current value, or with an argument to set the value. ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.