#! /usr/bin/perl -w # # elcapsul.pl -- Perl Object demo # Ed Cashin, April 1999 use strict; package Column; # this package could be in a separate file, Column.pm. # Then, if it was on the @INC path, you could "use Column;" # But it would need a "1;" at the end of the file. sub new { #-------this method is the "constructor" my $pkg = shift; my ($short_col_name, $pretty_col_name, $col_type) = @_; my %self = ( 'short_name' => $short_col_name, 'pretty_name' => $pretty_col_name, 'type' => $col_type, ); return bless \%self, $pkg; } # --------- these are "accessor methods". You don't absolutely need them # --------- in perl, but they often are worth using. sub short { my $self = shift || die "Error, method called without \"self\" reference."; return $self->{'short_name'}; } sub pretty { my $self = shift || die "Error, method called without \"self\" reference."; return $self->{'pretty_name'}; } sub type { #------this method allows you to set it as well as just read it. my $self = shift || die "Error, method called without \"self\" reference."; my $new_val = shift; if (defined $new_val) { $self->{'type'} = $new_val; } return $self->{'type'}; } package main; my $col_handle = new Column("mycol", "My Column", "varchar(80)"); print "New column with\n"; #------using the accessor methods print "\tshort name\t" . $col_handle->short . "\n"; print "\tpretty name\t" . $col_handle->pretty . "\n"; print "\ttype \t" . $col_handle->type . "\n"; print "\tnew type \t" . $col_handle->type("char(80)") . "\n"; #-------using the internal data directly (makes code maintenance harder) print "\n(without accessors)\n"; print "\tshort name\t" . $col_handle->{'short_name'} . "\n"; print "\ttype \t" . $col_handle->{'type'} . "\n";