In Perl, how to share a variable between subroutines, with use strict?

user1032613 picture user1032613 · Sep 28, 2012 · Viewed 15.8k times · Source

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.

Answer

ikegami picture ikegami · Sep 28, 2012

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!)