in reply to Modules Returning Values?
Generally the return value of the new() method of a module is the blessed reference to an object, which is an instance of the class its blessed into. Example:
package checkStuff; sub new { my $class = shift; my $bar = 2; bless \$bar, $class; return \$bar; # This line is redundant. } 1; package main; use strict; use warnings; my $obj = checkStuff->new(); print $obj, "\n"; print ref $obj, "\n"; __OUTPUT__ checkStuff=SCALAR(0x155ae0c) checkStuff
$obj is essentially your handle to the object instance created when you blessed $bar into class checkStuff. If you return something else instead of the object ref, you won't have access to the object anymore.
You can, however, return more than one thing via new() In the following example, a list is returned. The first element is the object reference. The second element is the value of $bar.
package checkStuff; sub new { my $class = shift; my $bar = 2; bless \$bar, $class; return ( \$bar, $bar ); # returning a list. } 1; package main; use strict; use warnings; my( $obj, $val ) = checkStuff->new(); print $obj, "\n"; print ref $obj, "\n"; print $val, "\n"; __OUTPUT__ checkStuff=SCALAR(0x155ae0c) checkStuff 2
What we've done here is defined new() to be both a constructor, and an accessor to $bar's value. This works fine, but isn't really convenient for repeated use, since you probably don't want to have to call $obj->new() each time you want to know what $bar holds, and
For that reason, accessors are usually defined in separate subs. For example, you could define within checkStuff a sub called getbar(). That sub would look like this:
sub getbar { my $self = shift; return ${$self}; }
...or more concisely...
sub getbar { return ${$_[0]}; }
Dave
|
|---|