Search code examples
perloopobjectperl-module

Passing object into the method Perl


I am dealing with the following problem. I am newbie in Perl.

The idea is that I have a class, it has array as member/field (in hash).
Let's name this class ProductContainer.

I have another class Product. These Classes are in separate files (separate modules). So I need to just add a Product object into ProductContainer object (internal array).

Simple example what I need in Java.

public class ProductContainer {
 private List<Product> mProductsList;
 public addProduct(Product product) {
  this.mProductList.add(product);
  }
}

Solution

  • It's not clear what exactly you are asking, as you haven't shown any Perl code.

    If you are using bless for your objects, the following shows you how to do that. I put all the packages in the same file. Also, note that the add method checks the type of its argument.

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    {   package ProductContainer;
    
        use Carp;
    
        sub new { bless {}, shift }
    
        sub add {
            my $self = shift;
            my $product = shift;
            croak "Invalid member" unless UNIVERSAL::DOES($product, 'Product');
            push @{ $self->{mProductsList} }, $product;
        }
    }
    
    {   package Product;
    
        sub new {
            my $class = shift;
            bless { name => shift }, $class
        }
    }
    
    my $p  = 'Product'->new('Product 1');
    my $pc = 'ProductContainer'->new;
    $pc->add($p);
    $pc->add('Product 2');   # Exception!