-1

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)

Acsor
  • 883
  • 1
  • 11
  • 24

3 Answers3

6

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;
amon
  • 54,982
  • 2
  • 82
  • 143
1

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

mpapec
  • 48,918
  • 8
  • 61
  • 112
  • Yeah, it works. But didn't my keyword modified scope between functions? Why is my $global also visible to other subroutines declaring it above? – Acsor Jul 10 '13 at 11:04
  • variables declared with `my` in most outer scope are visible to all below code regardless if in subroutine or not. – mpapec Jul 10 '13 at 11:05
  • Ok but, how is it possible the example above? – Acsor Jul 10 '13 at 11:08
  • check `my` vs `our` and how they actually behave http://stackoverflow.com/a/885888/223226 – mpapec Jul 10 '13 at 11:10
  • 2
    `our` variables always reference the fully qualified package variable `${__PACKAGE__}::VariableName` which is not lexically scoped like a `my` variable. What is lexically scoped is the alias `$VariableName`. – Joel Berger Jul 10 '13 at 11:52
  • Thanks to both. I had forgotten that my variables are only scoped to the enclosing block and that you can define subroutines everywhere in the code. – Acsor Jul 10 '13 at 12:18
1

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;
ikegami
  • 322,729
  • 15
  • 228
  • 466