click on the Biowiki logo to go to homepage
Edit Raw Print
Links Diffs RSS
About Stats Recent


Research Teaching Blog
Fall09 | Sandbox
Biowiki > Teaching > Bio E 131 > Diffusion Limited Aggregation Homework > ObjectUse

Search

Advanced search...

Topics

PageRank Checker

Perl Objects and Modules - The Uber-Short Users Guide

Modules

When you want to use someone else's code in perl, you use what are called perl modules. Refer back to slides 129+ from the lectures for a refresher, or see the Wikipedia page on the topic. Briefly, after the module has been installed (the GD module has been installed for you on the Etcheverry 1171 machines), you can just use code from that module in your own via the use statement. For example, let's suppose somebody else wrote a method called printNiftyASCII that knew how to print several images out as ascii characters, and stored that in a module called NiftyPrinter. In your code, you would write:


use NiftyPrinter;

# Bunch of random code 
.
.
.
printNiftyASCII("Dog");
#Bunch more random code
.
.

Notice that you never have to define a subroutine called printNiftyASCII, because you're using the version of it in NiftyPrinter package. Just as you can include procedural subroutines via the use statement, you can also include object written by other people.

Objects

For a review, see slides 130-135 in the perl lecture notes! Objects are a way of encapsulating both data and functions into a single entity, which often represents some sort of conceptual object. For example, you might have a FileReader object. You could make such an object by telling it what the name of the file it should work with is. You could then ask it to give you a single line of text from the file, or find all occurrences of the world "today" in the file, or any other interesting operation. Or, you might have a Class object. This might store information about who the instructor is, what students are enrolled, where the class is held, etc. You might want to have a particular class add or drop students, or change rooms, etc.

The syntax for using objects in perl is pretty straightforward. You first create a particular instance of an object (that is, there can be hundreds of classes on campus - you want to make a new one and have it be BE131). This is accomplished using the new function:

$bioEClass = Class->new("BioE131");

This will create a new Class object, and return a reference to it. Notice that, just like any other function, you can pass values to the new function. Just like every other reference we've used before, we'll have to use '->' when working with our object reference. For example, lets suppose our Class object can add a professor:

$bioEClass->addProfessor("Ian Holmes");

And that's all there is to it! At least for this assignment wink

-- JoshKittleson - 19 Nov 2007

Actions: Edit | Attach | New | Ref-By | Printable view | Raw view | Normal view | See diffs | Help | More...