in reply to Re^3: globally seen variable
in thread globally seen vairable

I declared
our $ERROR_FILE = $cgi_dir."files/logs/errors.txt";
in main program and tried to use it in package:
use strict; package RecordError; sub RecordError { my $error = shift; ## $ERROR_FILE is global var ## open OF, ">>$ERROR_FILE" or die "cannot open ERROR_FILE $ERROR_FILE\n" +; print OF "$error\n"; close OF; } 1;
and it returns
Global symbol "$ERROR_FILE" requires explicit package name at E:/..... +./lib/RecordError.pm line 12.
What do I do wrong?

Replies are listed 'Best First'.
Re^5: globally seen variable
by moritz (Cardinal) on Sep 29, 2010 at 08:41 UTC
    Contrary to the example you gave previously, you now seem to have the two snippets in question in different files. Which means that they don't share a lexical scope. So my explanation with lexical aliases doesn't apply in the new case.

    A lesson you can learn from is that it's not efficient to ask very general questions first, if you really want to solve a specific problem; neither is asking a question that doesn't actually demonstrate the problem.

    To answer your question, you need to either declare a lexical alias in each scope, to the same variable in the same package, or you need to qualify the namespace in one of the locations:

    { our $ERRORFILE = 'foo'; } { package RecordError; print $main::ERRORFILE, "\n"; }
    Perl 6 - links to (nearly) everything that is Perl 6.
Re^5: globally seen variable
by BrowserUk (Patriarch) on Sep 28, 2010 at 21:44 UTC

    You need to use our $ERROR_FILE; in each scope in which you need visibility.

    Rather than this comment....

    ## $ERROR_FILE is global var ## open OF, ">>$ERROR_FILE" or die "cannot open ERROR_FILE $ERROR_FILE\n" +;

    This serves the same purpose, and gives you that visibility.

    our $ERROR_FILE; open OF, ">>$ERROR_FILE" or die "cannot open ERROR_FILE $ERROR_FILE\n" +;

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      I did it, but it does not pass a value into $ERROR_FILE in the package.
      I defined our $ERROR_FILE in main and assigned a variable to it, not a constant. Is it possible?

        junk.pl:

        #! perl -slw use strict; use Junk; our $ERROR_FILE = 'fred'; Junk::showIt();

        Junk.pm:

        package main; our $ERROR_FILE; package Junk; use strict; use warnings; sub showIt { print $ERROR_FILE; } 1;
        C:\test>junk.pl fred

        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.