and then in World.pm#!/usr/bin/perl -w use strict; use World; # object oriented hello world my $USA = World->new('English'); my $foo = new World; $USA->greet; $foo->greet;
Trivial example, but imagine writing this (same functionality) in procedural code. You might be able to fake it with some closures or a handrolled lookup table, but when you have data that lends itself to the object model it pays to use OO. In the few lines above we have class data (%greetings), class methods (new), instance data ($self->{'language'}), and instance methods (greet). And once we've built our class, we have very few instructions to get a wide variety of greetings going. Imagine localizing more IO routines this way...#filename World.pm (easiest to put in same directory with calling scri +pt) package World; my %greetings = ( 'english' => 'Hello, World!', 'german' => 'Guten Tag, Welt!', 'latin' => 'Salve, Munde!', ); sub new { my $class = shift; #default language is Latin my $language = lc( shift ) || 'latin'; my $self = {}; #check to make sure the language is valid $self->{'language'} = (grep( /$language/, (keys %greetings)))[0] | +| 'latin'; bless $self, $class; return $self; } sub greet { my $self = shift; my $language = $self->{'language'}; print $greetings{$language}."\n"; } 1;
In reply to (ichimunki) Re: Reactions to OO-Perl
by ichimunki
in thread Reactions to OO-Perl
by pjf
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |