I was doing some maintenance on some old perl code and came across an odd api. Seems that this module receives an object reference as part of it's API, then calls methods in the other object without actually "use'ing" the other ojbect. Is this good practice? Is there a better way?
Here's a cheesy (but accurate) example of the technique I am talking about:
#!/usr/bin/perl -w
use Data::Dumper;
use strict;
package Apple;
sub new {
my $obj = shift;
my %self = ( color => 'red' );
bless \%self, $obj;
}
sub serve {
return 'sliced';
}
package Orange;
sub new {
my $obj = shift;
my %self = ( color => 'orange' );
if ( @_ ) {
$self{apple} = shift; ## other objects
$self{shape} = shift;
}
bless \%self, $obj;
}
sub serve {
my $self = shift;
return ( $self->{apple} ) ? $self->{apple}->serve() : 'squeezed';
}
package main;
my $red = new Apple;
my $yel = new Apple;
$yel->{color} ='yellow'; ## or is it better to pass to the new() for
+initialization.
my $foo = new Orange();
my $baz = new Orange( $red ); ## is it wise to pass an object ref vs.
+ "use'ing" the package
for my $obj ( $red, $yel, $foo, $baz ) {
print 'served: ', $obj->serve, "\n";
}
print "\n fruit stand: \n"
, Dumper($red)
, Dumper($yel)
, Dumper($foo)
, Dumper($baz)
, "\n";
Thanks for any guidance or recommendations!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.