Search code examples
perlclass-variables

why does perl constructor not initialize the package(class) variables


when perl constructor is called ,class reference is passed to the new function but constructor doesn't initialize class variables like java or c++ does.Instead it creates a new Hash and blesses it in class reference and returns it.This creates the problem that subroutines can't directly refer to variables they have to use the implicit reference passed.

The below code will highlight the issue:-

package foo;
use strict;
my $var1;
my $var2;
my $var3;

sub new {
    my $class = shift;
    my $self  = {
        var1 => shift,
        var2 => shift,
        var3 => shift
      };

    bless $self, $class;
    return $self;

      }

sub method {

        my $self = shift;
        print(
            "variable value are $self->{var1},$self->{var2},$self->{var3}";
       #how to directly refer to var1 declared above? instead of self->{var1} 
       }

clearly the package method has to use the reference self to use var1,var2,var3 which is are not the package variables but only the hash's objects.

1:-what this means is in perl there is no way to initialize the package variables?? 2:-if i initialize them explicitly in some method,would they have one copy for all objects or different copy per object


Solution

  • The canonical way to use package variables is to declare them with our. Outside the package, you can refer to them by qualifying the variable name with the package.

    package foo;
    our ($var1, $var2, $var3) = (5, 42, "bar");
    sub new { bless { var4 => $_[1] }, $_[0] }
    ...
    1;
    
    
    package main;
    use foo;
    $obj = foo->new(19);   # instance of foo
    print "Instance variable is $obj->{var4}\n";    # 19
    print "Package variable is $foo::var1\n";       #  5