I was wondering if I could use some globals variables while using strict pragma.

For example, I've tried to do this:

#!/usr/bin/perl -w

use strict;

sub print_global{
     print "your global is: $global\n";
}

$global = 1234;     #or even my $global = 1234;

print_global;

But as you can notice it doesn't work.

Are there any ways to define global variables when using strict pragma? (if any, of course)

有帮助吗?

解决方案

Just declare the global before using it:

our $global;

Unlike my, this does not create a new variable, but rather makes the variable available in this scope. So you could safely have code like

sub print_global{
     our $global;  # does not create a new variable like `my` would
     print "your global is: $global\n";
}

our $global = 1234;

print_global;

其他提示

Declare my $global; above your function and it'll work with use strict;.

use strict; tells Perl you wish to be forced to declare your variables, and you did not do so. Add a declaration where appropriate.

#!/usr/bin/perl -w

use strict;

my $global;     # <----

sub print_global{
     print "your global is: $global\n";
}

$global = 1234;
print_global;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top