Dragos Trif
Dragos Trif

Reputation: 302

Can't use Moo class properly before it's declaration in the same script

Please have a look at the script below. The first call to do_stuff(...), although it works without errors, prints names: $VAR1 = undef;.

The second call to do_stuff(...), works as I expect it to work and prints names: $VAR1 = 'Second Name';

And i have some questions:

  1. What package Foo is used when do_stuff is called for the first time?
  2. Shouldn't the compiler throw an error instead of using what looks like an improper class?

The code:

use warnings;
use 5.018;
use Data::Dumper;

do_stuff('First Name');

{
package Foo;
use Moo;
use Data::Dumper;

has names => (is => 'ro', required => 1);

sub get_name {
  my $self = shift;

  say "names: ".Dumper($self->{names});

}

1;
}

do_stuff('Second Name');

sub do_stuff{
   my $names = shift;
   my $x = Foo->new(names => $names);
   $x->get_name();
}

Upvotes: 1

Views: 25

Answers (0)

Related Questions