habit_forming has asked for the wisdom of the Perl Monks concerning the following question:

Oh great and erudite Monks, edifying are thy words and calming thy code in a mind bent by fascination with Perl.
Please hear my question.

Why does this piece of code:
#!/usr/bin/perl use warnings; use strict; package Foo; our $bar = 16; my $foo = 15; package main; our $bar = "bar\n"; my $foo = "foo\n"; print "bar = $bar\n" print "foo = $foo\n"
Give this error:
"my" variable $foo masks earlier declaration in same scope at ./b.pl l +ine 13. syntax error at ./b.pl line 16, near "print" Execution of ./b.pl aborted due to compilation errors.
They _should_ be in completely different scopes... shouldn't they??

--habit

Replies are listed 'Best First'.
Re: packages within the same file.
by chromatic (Archbishop) on Aug 01, 2003 at 18:16 UTC

    Package declarations don't introduce new scopes. Blocks do and files do.

Re: packages within the same file.
by derby (Abbot) on Aug 01, 2003 at 17:58 UTC
    Variables declared with my are lexical. From the perldoc of package:

    A package statement affects only dynamic variables--including those you've used "local" on--but not lexical variables

    -derby

Re: packages within the same file.
by bobn (Chaplain) on Aug 01, 2003 at 19:11 UTC

    You clould get around this with curlies:

    our $bar; { package Foo; $bar = 16; my $foo = 15; } { package main; $bar = = "bar\n"; my $foo = "foo\n"; print "bar = $bar\n"; print "foo = $foo\n"; }
    Note that I may not have done what you meant to do with $bar
    --Bob Niederman, http://bob-n.com
Re: packages within the same file.
by smalhotra (Scribe) on Aug 01, 2003 at 18:29 UTC
    You are missing a semicolon ( ; ) at the end of your print statements, that's your sytax error. The other is just a kind, and gentle warning. Try to use diagnostics;, it gives to more information about what might have gone wrong.

    $will->code for @food or $$;

Re: packages within the same file.
by simonm (Vicar) on Aug 01, 2003 at 18:28 UTC

    Unlike package variables, lexical ("my") variables are scoped to the end of the enclosing pair of curly brackets, or to the end of the file.

Re: packages within the same file.
by skyknight (Hermit) on Aug 01, 2003 at 19:00 UTC

    You can put multiple packages into one file... but don't. You will just make your life needlessly painful. I speak out of personal experience. If you follow the "one package, one file" rule, you will avoid all kinds of nastiness. The only exception to this rule would be if you wanted a private-ish package, though it wouldn't even be all that private. So, best tip: don't.