Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function to constructor

Tags:

perl

How to pass a function to constructor, so the class could use it internally?

test.pl

use Class;
use Loger;

my $loger = Loger->new();
$loger->log('I have logger now, I can log messages!');

my $class = Class->new(\&{ $loger->log }); # here we pass the function (the method of other class) to contructor of a new  Class

$class->do_something();  # class uses loger->log internally to report errors

Class.pm package Class;

sub new {

    my $self = {};
    $self->{log} = shift; # we got logger->log function, save it for future use

    return bless $self;
}

sub do_something {
     my $self = shift;

     open_file or $self->{log}->('Cant open file'); # we can use gotten logger in class 
}


1;
like image 666
xoid Avatar asked Mar 13 '26 19:03

xoid


1 Answers

You are trying to pass a method, not a function (or sub). Calling it on its own will not work. If you want an object's method, pass the object and call the method on the object.

my $loger = Loger->new();
$loger->log('I have logger now, I can log messages!');

my $class = Class->new(logger => $loger); # pass the Loger object

And in Class.pm:

package Class;

sub new
{
  my ($class, %args) = @_;
  my $self = {};
  $self->{log} = $args{'logger'}; # store it inside your Class object
  return bless $self;
}

sub do_something
{
   my $self = shift;
   open_file or $self->{log}->log->('Cant open file'); # call its log-method
}
like image 200
simbabque Avatar answered Mar 15 '26 12:03

simbabque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!