Perl Class Globals

This first post is on Perl, specifically class globals AKA class variables (for Java programmers.) This is mostly so I can figure out how easy it’s going to be to write code on this blog, and to test the server configuration so I can make sure everything uploads OK.

So here’s a contrived example: A class that keeps track of the number of instances of itself.

In Foo.pm

#!/usr/bin/perl
use warnings;
use strict;

my $CLASS_COUNTER;

sub new {
 my ($class) = @_;
 $CLASS_COUNTER++;
 my $self = {};
 bless $self, $class;
}

sub get_count {
 return $CLASS_COUNTER;
}

Each time a Foo is instantiated, the class counter gets incremented. This is different than adding a variable to the $self hash, it is stored once per class, not once per instance.

So why would you want to do this? Well the example that came up at work today was an object that has a short (read small in memory) ID that is a key in a larger hash encoding plain English versions of this key. So what we did was store only the short key in $self, and store 1 copy of the translation hash as an object global. The ‘get_key()’ method then looked up the translation and returned the full string, without storing those full strings in a million objects

This entry was posted in Software Development and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">