perlperl5.8

How to correctly import a function from a custom module


I need some clue on how to import correctly a function from a custom module in perl. (here person_init from the PersonInit module).

This is my folder representation :

TestObject.pl
Person/Person.pm
Person/PersonInit.pm

here is the code of TestObject.pl

use FindBin 1.44 qw( $RealBin );
use lib $RealBin;
use warnings;        # Avertissement des messages d'erreurs
use strict;  
use Person::PersonInit;

person_init();
print('toto');

in Person.pm :

package Person;    # Nom du package, de notre classe
use warnings;        # Avertissement des messages d'erreurs
use strict;          # Vérification des déclarations
use Carp;            # Utile pour émettre certains avertissements
sub new {
  my ( $classe, $ref_arguments ) = @_;

  # Vérifions la classe
  $classe = ref($classe) || $classe;

  # Création de la référence anonyme de hachage vide (futur objet)
  my $this = {};

  # Liaison de l'objet à la classe
  bless $this, $classe;

  if (! ( defined $ref_arguments->{nom} )) {
    $ref_arguments->{nom} = 'inconnu';
  }

  $this->{_NOM}          = $ref_arguments->{nom};
  $this->{_PRENOM}       = $ref_arguments->{prenom};
  $this->{_TEL}           = $ref_arguments->{tel};
  $this->{_MAIL}           = $ref_arguments->{mail};
  $this->{_GRADE}           = $ref_arguments->{grade};
  $this->{_SEXE}         = $ref_arguments->{sexe};
  $this->{_SERVICE}         = $ref_arguments->{service};

  return $this;
}
1;                # Important, à ne pas oublier
__END__ 

and in PersonInit.pm :

#/usr/bin/perl
package PersonInit;
use strict;
use POSIX;
use warnings;

use FindBin 1.44 qw( $RealBin );
use lib $RealBin;
use Person::Person;
use Exporter;

our @ISA= qw( Exporter );

# these CAN be exported.
our @EXPORT_OK = qw( person_init );

# these are exported by default.
our @EXPORT = qw( person_init );



sub person_init {
my ($arg) = @_;
my $Person = Person->new({
    prenom        => 'Jean',
    sexe          => 'M',
    tel => '3',
    mail  => '4',
        grade  => 'g',
        service  => 's',
  });
  print ($Person->{_NOM});
  print ('toto');
  return $Person;
 };

1;

So when i try to launch t i've got this error :

Undefined subroutine &main::Person_Init called at D:\Workspace\Mapping\TestObject.pl line 8.


Solution

  • For best results, the package names you use should match the package names you supply to the use directive. Use

    package Person;
    ...
    package PersonInit;
    ...
    use Person;
    use PersonInit;
    

    or

    package Person::Person;
    ...
    package Person::PersonInit;
    ...
    use Person::Person;
    use Person::PersonInit;
    

    but not

    package Person;
    ...
    package PersonInit;
    ...
    use Person::Person;
    use Person::PersonInit;