Why do some Global symbols require an explicit package name

Viewed 66

Why does line 18 required explicit package name in the code below?

#! /usr/bin/env perl

use strict;
use warnings;
use utf8;
use feature qw<say state>;

{
    no strict;
    no warnings;

    $myRef{G4143} = 58;
    $myRef{Emily} = 8;
    $myRef{Angela} = 40;

}

#%myRef requires explicit package name
while (my ($key, $value) = each %myRef) {
    say "$key=>$value";
}

exit(0);

If I add the main package to %myRef on line 18, then it works

#! /usr/bin/env perl

use strict;
use warnings;
use utf8;
use feature qw<say state>;

{
    no strict;
    no warnings;

    $myRef{G4143} = 58;
    $myRef{Emily} = 8;
    $myRef{Angela} = 40;

}
#added package name and now it works
while (my ($key, $value) = each %main::myRef) {
    say "$key=>$value";
}

exit(0);

Why is the package name required in this example?

1 Answers

You need to explicitly specify the package name because

  1. strict is enabled and
  2. %myRef has not been declared (using my, our, or use vars) in that scope or any enclosing scope

You don't need the package name in the earlier block because strict is turned off within that block.

If you add the line my %myRef; (or our %myRef; if you want it to be visible outside of the current file and package) before the no strict block, then you will no longer need the explicit package name, nor will you need no strict within the block.

And the no warnings is already superfluous, so I would recommend removing it. There's nothing in that block that would generate a warning in any case.

Related