#! /usr/bin/perl -T # Tpkg.pm Daniel Brockman 070205 Package for demonstrating object creation. ################################################# # The author grants permission to use for any # # purpose, including copying and modification, # # provided the user acknowledges the author by # # name. (Creative Commons Attribution License # # http://creativecommons.org/licenses/by/2.5/ ) # # -- Daniel Brockman, author, 20070205 # ################################################# # # # Intended for use with program HowToCreate.pl . # # Imho, the books "Programming Perl" and "Perl Cookbook" # almost tell you how to create and use an object, but # not quite. Here is an example of one way to create a # practical object to supplement these texts. package Tpkg; use strict; use Carp; #----------------------------------------------- sub new { my $class = shift; if(@_ % 2) { croak "Default options must be name=>value pairs (odd number supplied)"; } my $self = {}; # allocate new memory my %args = @_; # pick up args while (my($key,$val) = each %args ) { # loop arguments $self->{$key} = $val; # assign to object # print "L18 val:$val\n"; # test } # end loop arguments return(bless($self,$class)); # instantiate new obj. }; #----------------------------------------------- sub prtvals { my $self = shift; my ($key,$val); foreach $key ( keys %$self ) { $val=$self->{$key}; print "prtvals: key:$key val:$val (val:$self->{$key})\n"; } } # end prtvals #----------------------------------------------- #----------------------------------------------- 1