Richard Lee wrote:
> Rob Dixon wrote:
>> Richard Lee wrote:
>>
>>> I was just testing out the code from the book 'writing perl modules for
>>> cpan' and I am trying out below module and getting compiled error.
>>> I cannot/donot see what is wrong w/ the code.
>>>
>>> can anyone see?
>>>
>>> use strict;
>>> use warnings;
>>>
>>>
>>> package BOA::Logger2;
>>> use Carp qw(croak);
>>> use IO::File;
>>>
>>> #constructor - returns new BOA::Logger2 objects
>>> sub new {
>>> my ($pkg, $filename) = @_;
>>>
>>> #initialize $self as a reference to an empty hash
>>> my $self = {};
>>>
>>> #open the log file and store IO::File object in $self->{fh}
>>> my $filehandle = IO::File->new(">>$filename");
>>> croak("Unable to open $filename: $!") unless $filehandle;
>>>
>>> #print startup line
>>> $filehandle->print("BOA log started: " . localtime(time) . "\n");
>>>
>>> #store the filehandle in $self
>>> $self->{fh} = $filehandle;
>>>
>>> #set default log_level of one
>>> $self->{level} = 1;
>>>
>>> #bless $self as an object in $pkg and return it
>>> bless($self, $pkg);
>>> return $self;
>>> }
>>>
>>> # level method - changes log level for this log object
>>> sub level {
>>> my ($self, $level) = @_;
>>> $self->{level} = $level;
>>> }
>>>
>>> # write method - writes a line to the log file if log-level is high enough
>>> sub {
>>> my ($self, $level, $message) = @_;
>>> $self->{fh}->print($message) if $level <= $self->{level};
>>> }
>>>
>>>
>>> 1;
>>>
>> You haven't named the last subroutine :)
>>
>> Rob
>>
> I am using above w/ this simple program.
When you say 'above' do you mean 'the above, but with the final subroutine
named'?
> use strict;
> use warnings;
>
> use lib './cpan_pratice';
> use BOA::Logger2;
> my $logger = BOA::Logger2->new('logs/boa.log');
> $logger->level(10);
> $logger->write(10, "Hello world!\n");
>
> and works fine.
>
> I am trying to pick apart the pm example but
>
> my ( $pkg, $filename ) = @_;
>
> do not really understand.
> I am calling above w/
>
> my $logger = BOA::Logger2->new('logs/boa.log');
>
> according to the book, it says ' a class method that returns new
> objects. new() receives 2 arguments - the name of the package
> and the filename to open'
>
> I don't understand how BOA::Logger2 is being passed over.. I am thinking
> only what's inside bracket new() is being passed..
It is common practice in most languages to pass an additional implicit parameter
to method calls. Class methods like BOA::Logger2->new will have the class name
passed as the first parameter, whereas object methods like $logger->level will
have the object pass the object in the same place. That is really the only
difference between calling
BOA::Logger2->new('logs/boa.log')
and
BOA::Logger2:new('logs/boa.log')
The first is a method call and so will have the class name passed as well as the
parameter you provide explicitly.
HTH,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/