[Chicago-talk] default methods

Steven Lembark lembark at wrkhors.com
Tue Jul 27 01:07:49 CDT 2004



-- JT Smith <jt at plainblack.com>

> Oooh. Thanks for this tip. That's good to know too. I'll definitely have
> a look at Shell.

	use Shell qw( ls du df );

	my $a = df '-m', '/home/diskhog';
	my $b = du '-ms', '/home/diskhog';



basically all Shell does is have an autoloader that returns
qx( @_ ) for items you've installed. A kwikhak version looks
something like:

	my %known = ();

	sub import
	{
		my $module = shift;

		my $caller = caller;

		%known = map { $caller . '::' . $_ => $_ } @_;
	}

	sub AUTOLOAD
	{
		my $name = $known{$AUTOLOAD}
			or die "Unknown: $AUTOLOAD";

		qx( $name @_ );
	}

Point here is that the AUTOLOADER doesn't have to install anything.
All this one does is store fully qualified names for the shell
commands and run the ones it's seen use-ed in that package.

The trick with statement handles is someting I'm working on here.
Idea is to have the derived classes provde nothing more than some
metadata and a constructor. The base class provides an initializer
and the AUTOLOAD.

Construction in most cases just blesses a reference to common
metadata into the requested class. Values are SQL that is
prepare-ed at call-time.

This allows for things like:

	package Lookup::Blah;
	use base Lookup;

	my %template =
	(
		blah_id => q{select blah_id from blah where blah_name = ?},

		...
	);

	sub construct
	{
		my $item = shift;

		my $obj = bless \%template, ref $item || $item

		$obj->init
	}

	package Lookup;

	my $dbh = blah();

	sub init
	{
		my $obj = shift;

		# load any shared metadata.
		# munge queries for pretty-printing.

		$obj->{dbh} ||= $dbh;

		# hand back the object.

		$obj
	}

	sub AUTOLOAD
	{
		# check for key, prepare statement handle,
		# return results.

		my $sth = ...

		my $sub =
		sub
		{
			# dump the object itself.

			shift;

			$sth->execute( @_ );

			my $a = $sth->fetchall_arrayref;

			if( @{$a->[0]} == 1 )
			{
				$_ = $_->[0] for @$a;
			}

			$a = $a->[0] if @$a == 1;
		};

		no strict ref's.
		
		*$AUTOLOAD = $sub;

		goto &$AUTOLOAD
	}

with the caller just using the key-names as methods:

	# inexpensive since the constructor does no real
	# work, the preparation comes only when the method
	# (query) is actually called.

	my $obj = Lookup::Blah->construct;

	my $a = $obj->blah_id( $name );



-- 
Steven Lembark                           9 Music Square South, Box 344
Workhorse Computing                                Nashville, TN 37203
lembark at wrkhors.com                                     1 888 359 3508



More information about the Chicago-talk mailing list