Domanda

If I don't use strict; the following code works fine and prints out "alice":

assign_name();
print_name();

sub assign_name {
    $name = "alice";
}

sub print_name {
    print $name;
}

However when I do use strict; then I know I'll have to declare the variable before using it. I read somewhere I should use our instead of my to declare a global variable. So I had the following:

use strict;
use warnings;

assign_name();
print_name();

sub assign_name {
    our $name = "alice";
}

sub print_name {
    print $name;   # This is line 12.

}

And then I get the following error:

Variable "$name" is not imported at test.pl line 12.
Global symbol "$name" requires explicit package name at test.pl line 12.
Execution of test.pl aborted due to compilation errors.

Please help.

È stato utile?

Soluzione

Just declare the variable where both subs can see it.

use strict;
use warnings;

my $name;

assign_name();
print_name();

sub assign_name {
    $name = "alice";
}

sub print_name {
    print $name;
}

(There's no reason to use our here!)

Altri suggerimenti

I know this is beyond the scope of your question, and ikegami's answer answers it nicely, still I think there is more to be said. If you have functions that are mean to change package-scoped variables, likely you could do better rewriting those variables as object attributes. In Perl we can do that using Moose.

#!/usr/bin/env perl

use strict;
use warnings;

{ # proper use of scoping, h/t tchrist

  package Person;

  use Moose;
  use namespace::autoclean; # recommended

  has 'name' => ( is => 'rw', isa => 'Str', required => 1);

  __PACKAGE__->meta->make_immutable; # recommended

}

my $person = Person->new( name => 'Joel' );
$person->name( 'Adam' ); # change name

print $person->name . "\n";

In this example we make a name attribute, we can set it during object construction, then change it or view it using accessor methods. The data that would have been global, in this case the name, is then contained inside the object's internal data. This allows different parts of your code to reuse that same logic without worrying about the state of that global data.

You should declare the global variable upper :

use strict;
use warnings;

my $name;

assign_name();
print_name();

sub assign_name {
    $name = "alice";
}

sub print_name {
    print $name;   # This is line 12.
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top