why the fourth of these examples is an error

I'd say it's in accordance with strict (emphasis mine):

strict vars

This generates a compile-time error if you access a variable that was neither explicitly declared (using any of my, our, state, or use vars ) nor fully qualified.

(Edit: to re-phrase, maybe it's more clear -- was neither explicitly declared nor is fully qualified.)

Thus, no surprise that next 2 lines fail:

perl -wMstrict -e "$::x=0; $x++" # not OK perl -wMstrict -e "package foo; $foo::x=0; $x++" # not OK

Next 2 lines are your examples -- it's strange 2nd (your third) doesn't fail:

perl -wMstrict -e "BEGIN{*::x=\$a} $x++" # not OK (1) perl -wMstrict -e "BEGIN{package foo; *::x=\$a} $x++" # OK (2)

It has something to do with BEGIN:

perl -wMstrict -e "{package foo; *::x=\$a} $x++" # not OK

the deparsed output is an insult:

C:\>perl -MO=Deparse -wMstrict -e "{package foo; *::x=\$a} $x++" Variable "$x" is not imported at -e line 1. Global symbol "$x" requires explicit package name (did you forget to d +eclare "my $x"?) at -e line 1. -e had compilation errors. BEGIN { $^W = 1; } use strict; { package foo; *main::x = \$a; } $main::x++;

But also with "main" package. Next 2 are symmetrical with examples (1) and (2), just with "bar" instead of "main", but both OK now:

perl -wMstrict -e "BEGIN{package bar; *bar::x=\$a} package bar; $x++" + # not OK perl -wMstrict -e "BEGIN{package foo; *bar::x=\$a} package bar; $x++" + # OK

Edit 2: Actually, replacing "main" with "bar" doesn't change anything (fixed one of the lines above).


In reply to Re: Logic for importing and strict vars? by vr
in thread Logic for importing and strict vars? by haukex

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.