package Student; #tell Perl we're creating a new class called Student sub new{ #begin constructor my $class = shift; #class name is first argument passed to function my $ref = {Name => "", ID => 0}; #initialize class variables bless($ref, $class); #associate reference with this class return $ref; #return the new class object } #Now we have two class methods to set variables, and two to read variables sub set_name{ my $ref = shift; #get the object we're operating on my $name = shift; #get the value of the name passed in $ref->{'Name'} = $name; #assign the Name parameter to be what was passed in } #this function is virtually identical to the first sub set_RIN{ my $ref = shift; my $rin = shift; $ref->{'RIN'} = $rin; } #now we have two functions to read the values stored sub get_name{ my $ref = shift; #get the object we're operating on my $name = $ref->{'Name'}; #find the Name parameter of that object return $name; #return that parameter } #deja vu sub get_RIN{ my $ref = shift; return $ref->{'RIN'}; } 1; ---------------------------------------------------------------------- #!/usr/local/bin/perl -w use Student; #first, tell Perl we'll be using the Student class we created #create two new instances of the class Student (using two different methods) $s1 = new Student; $s2 = Student->new; #Set the names of each student $s1->set_name("Paul Lalli"); $s2->set_name("Justin McGuire"); #set the RINs of each student $s1->set_RIN(123121); $s2->set_RIN(897907); #Here we create a hash of students, keyed by name, with RINs as values %students = ($s1->get_name => $s1->get_RIN, $s2->get_name => $s2->get_RIN); #Print out each student's info foreach $name (keys %students){ print "Student with name $name has RIN $students{$name}\n"; } -------------------------------------------------------------------- #!/usr/bin/env perl -w use Math::Complex; $z = Math::Complex->make(5, 6); print "z first equals: $z\n"; #Two different ways of calling instance methods: $real = $z->Re(); $img = Math::Complex::Im($z); print "The real part of $z is $real, and the imaginary part is $img\n"; #Using overloaded = and +, and constant i $y = 4 + 3*i; print "y = $y\n"; $ry = $y->Re(); $iy = $y->Im(); print "Real y = $ry\tImg y = $iy\n"; #More overloading $x = 10 + 5*i + $z; print "x = $x\n"; $rx = $x->Re(); $ix = $x->Im(); print "Real x = $rx\tImg x = $ix\n"; #Setting pieces of complex numbers, the way the writer intended $x->Re(20); $x->Im(40); print "x is now = $x\n"; #Demonstrating that class variables are not private ${$z->cartesian}[0] = 40; #Don't do this!!! $real = $z->Re(); $img = Math::Complex::Im($z); print "The real part of $z is $real, and the imaginary part is $img\n";