Acsor
Acsor

Reputation: 1061

Using global variables with strict pragma in Perl

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)

Upvotes: 0

Views: 6217

Answers (3)

ikegami
ikegami

Reputation: 386481

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;

Upvotes: 1

amon
amon

Reputation: 57640

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;

Upvotes: 6

mpapec
mpapec

Reputation: 50667

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

Upvotes: 1

Related Questions