$hex = sprintf(''%02X%02X%02X'', $red, $green, $blue);for an rgb triplet ($red, $blue, $green). The problem we are going to examine is to write a function which takes in the rgb values and calculates for us the hexadecimal equivalent.
Using a function-oriented approach, we might be led to consider the following module, which exports a routine rgb2hex.
package RGB1; use strict; use base qw(Exporter); our (@EXPORT_OK); @EXPORT_OK = qw(rgb2hex); sub rgb2hex { my $rgb = shift; my $hex = sprintf("%02X%02X%02X", $rgb->[0], $rgb->[1], $rgb->[2]); return $hex; } 1;This can used in a script as follows:
use strict; use RGB1 qw(rgb2hex); my @rgb = (255, 33, 158); my $hex = rgb2hex(\@rgb); print "The hexadecimal equivalent is $hex\n";
We are now going to convert the RGB1 module into one that uses an object-oriented interface. There are two main differences:
package RGB2; use strict; sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } sub rgb2hex { my ($self, $rgb) = @_; my $hex = sprintf("%02X%02X%02X", $rgb->[0], $rgb->[1], $rgb->[2]); return $hex; } 1;with an example of it's use being
use strict; use RGB2; my @rgb = (255, 255, 255); my $color = RGB2->new(); my $hex = $color->rgb2hex(\@rgb); print "The hexadecimal equivalent is $hex\n";What is happening here is the following. In the new method,
my $obj = RGB2->new();and all subsequent work is then done using this object. Note that, in object-oriented programming, methods are called using the arrow notation: RGB2->new().
When converting a function (subroutine) to use an object-oriented interface, one thing to keep in mind is that the object is passed into the method as the first parameter. Thus, in order to use the function
sub rgb2hex { my $rgb = shift; my $hex = sprintf("%02X%02X%02X", $rgb->[0], $rgb->[1], $rgb->[2]); return $hex; }in an object-oriented setting, we have to change capturing the parameters to
sub rgb2hex { my ($self, $rgb) = @_; my $hex = sprintf("%02X%02X%02X", $rgb->[0], $rgb->[1], $rgb->[2]); return $hex; }The object in a method is conventionally given the name $self. In the script, the method is then invoked as
my $hex = $rgb->rgb2hex(\@rgb);with the reference to the array @rgb appearing as the second paramter passed into the rgb2hex method.