In Foo.pm:
In im-oo-test.pl:#!/usr/bin/perl use strict; use warnings; package Foo; sub new { my $class = shift; bless { name => 'foo' }, ref($class)||$class; } sub bar { my $ref = ref $_[0]; if ($ref eq __PACKAGE__) { ## OO method call oo_bar (@_); } elsif ($ref eq 'HASH') { ## imperative subroutine call with hashref as first element im_bar (@_); } } sub oo_bar { my $self = shift; print "oo_bar got object named ", $self->{name}, "\n"; } sub im_bar { my $hr = shift; print "im_bar got hashref with name ", $hr->{name}, "\n"; } 1;
There's a zillion ways to proceed from this skeleton. You could use a naming scheme like Module::OO::sub() rather than oo_sub(), you could write one subroutine to handle both types of calls, you can make the ref $_[0] business a little cleaner with use UNIVERSAL 'isa'... you can even ignore whether a hashref is an object, provided it has the right keys and values in it.#!/usr/bin/perl use strict; use warnings; use Foo; my $hr = { name => 'hashref' }; my $obj = new Foo; ## OO method call $obj->bar; ## imperative call, but since $obj is a blessed object, ## this is equivalent to the OO call Foo::bar($obj); ## imperative call Foo::bar($hr);
I would consider it good programming practice to put maximum flexibility into how your subroutines may be called, as long as this flexibility doesn't introduce too much complexity on the backend. That's your call.
In reply to Re: Is it ok to mix functional and oo programming in one package?
by gamache
in thread Is it ok to mix functional and oo programming in one package?
by leocharre
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |