Weblog entry #7 for uroboros

BASH OOP
Posted by uroboros on Fri 2 Jun 2006 at 18:11
Tags: none.

I know that the code below is NOT real OOP, but it is really nice trick.

#!/bin/bash

# Object-oriented-like programming using pure BASH only:

persons.add ()
{
        local obj_name=$1
        local surname=$2
        local name=$3
        local birth=$4

        eval "$obj_name.set_surname ()
        {
                eval \"$obj_name.surname ()
                {
                        echo \$1
                }\"
        }"

        eval "$obj_name.set_name ()
        {
                eval \"$obj_name.name ()
                {
                        echo \$1
                }\"
        }"

        eval "$obj_name.set_birth ()
        {
                eval \"$obj_name.birth ()
                {
                        echo \$1
                }\"
        }"

        $obj_name.set_surname $surname
        $obj_name.set_name    $name
        $obj_name.set_birth   $birth
}

# Test database:

persons.add 1 'Tachion' 'Charles' '24/02/1979'
persons.add 2 'Quark'   'Carlos'  '05/06/1958'
persons.add 3 'Proton'  'Thomas'  '14/12/1997'

# Print out the test database:

for i in 1 2 3
do
       echo $i:\ `$i.surname`,\ `$i.name`\ \(`$i.birth`\)
done

# The end!

exit 0

The whole concept could be, oh yes, much more improved! I hope it helps!

--
MJF

 

User Login

Username:

Password:

[ Advanced Login ]

Register Account

Quick Site Search