Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

global var

by tultalk (Monk)
on Apr 05, 2017 at 19:57 UTC ( [id://1187183]=perlquestion: print w/replies, xml ) Need Help??

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

HI I have global var in main unit:

@EXPORT = qw( $LoggedOn_user_id $VERSION = '0.0.1'; } our $LoggedOn_user_id; my $username1 = $session->param("username"); warn("username1 : '$username1'"); my $text = $username1; $text =~ m/(\d+)/; my $num = $1; warn("num: '$num'"); $LoggedOn_user_id = $num; warn("is already logged on loggedon_user_id : '$LoggedOn_user_id'");

Above code works fine. $username1 from session is jala428. $num shows 428 as does $LoggedOn_user_id.

In another unit I have: use manageusers;

my $userid = 0; $userid = $manageusers::LoggedOn_user_id;

$userid in this unit shows 0. I have another global same main unit and pulling vatiable in another unit and works fine. Exact same method.

I did searches in all files in cgi directory after change to $userid_1:

my $userid_1 = 0; $userid_1 = $manageusers::LoggedOn_user_id; warn("userid : '$userid_1' "); #$userid_1 = 428; my $uid = $userid_1; my $uid = $userid_1;

All hits same file in question. No others. Fails with $userid_1 = 0;

Any observations/suggestions appreciated

Replies are listed 'Best First'.
Re: global var
by stevieb (Canon) on Apr 05, 2017 at 20:05 UTC

    I don't know exactly what the problem is, but stopped as soon as I saw this:

    @EXPORT = qw( $LoggedOn_user_id $VERSION = '0.0.1'; }

    There is all manner of wrong with that. Add use strict; and use warnings; to that code.

    • you can't have a ; in the middle of a quote-words (qw), unless you truly mean it to be there. qw() literally means "quote each item as a word"
    • you have no our before @EXPORT
    • you don't have a semi-colon after the instantiation of the @EXPORT array
    • you open the qw with a parens, but close with a brace
    • you can't interpolate variables in qw()
    • if this isn't your real code, please do post it.

    Lastly, use @EXPORT_OK instead of @EXPORT wherever possible, so you don't pollute other namespaces needlessly.

      Hi: Did not want to post tooooo much.

      package manageusers; use strict; use diagnostics -verbose; use warnings; use CGI; #use Carp::Always; use CGI::Carp qw(fatalsToBrowser warningsToBrowser); use CGI qw(:standard escapeHTML); use CGI qw/:standard/; use Data::Dumper; use Digest::MD5 qw(md5_hex); #use DB_File; # persistent hash database use CGI::Session; use CGI::Cookie; #use vars qw($session_cookie1 $session_cookie2 $login_timeout); #use vars qw($session); use Mail::Sendmail; use Time::HiRes qw(usleep); use Time::Local; BEGIN { use vars qw($VERSION @ISA @EXPORT); use DBI; # $ENV{DBI_TRACE}=1; # $ENV{PERL_DBI_DEBUG}=1; require Exporter; @ISA = qw(Exporter); # exported functions @EXPORT = qw( &OpenConnection &OpenSession &ProcessLoginRequest &ProcessLostDataRequest &LoginUser &decodeEncryptedPassName &UpdateUserData &GetUserLostData &LogoutUser &GetUserSessionCookie &CheckForAuthorizedUser &Expires $attempts $adminaccess $LoggedOn_user_id &Now &CheckValidLoginChar &CheckValidEmailChar &print_md5_javascript); $VERSION = '0.0.1'; }

      A good read

      How to Import In other files which wish to use your module there are three basic ways for them to load your module and import its symbols: use YourModule; This imports all the symbols from YourModule's @EXPORT into the namespace of the use statement. use YourModule (); This causes perl to load your module but does not import any symbols. use YourModule qw(...); This imports only the symbols listed by the caller into their namespace. All listed symbols must be in your @EXPORT or @EXPORT_OK , else an error occurs. The advanced export features of Exporter are accessed like this, but with list entries that are syntactically distinct from symbol names.

      I assume you recommend @EXPORT_OK and YourModule qw(...);

      Having clarified the code, is there anything you can see that would prevent my grabbing $userid_1 correctly?

      Now in reading this:

      When using Exporter with the standard strict and warnings pragmas, the our keyword is needed to declare the package variables @EXPORT_OK , @EXPORT , @ISA , etc.

      So now my function calls that used to work: Undefined subroutine &main::ProcessLoginRequest called at manage_users.cgi line 86.

      So now I have to change all these calls to $manageusers::ProcessLoginRequest. Is that correct? Or change use manageusers; to use manageusers qw(myimportlist);

      I guess posting too much is better than posting too little.

        See GotToBTru's post to create a proper example, but from your code, I see this:

        # exported functions

        That makes me think you copy/pasted something off of the Internet, and with the lines that follow that comment, it appears it closely resembles perl4 code (or someone coding perl5 that hasn't migrated to the perl5 mindset yet. This was nearly two decades ago!).

        I feel that you need some new resources to read, research and reflect upon. Is this a project that you were forced into and are trying to adjust by chance?

        To clarify (I hope) a few things about "use xxx;"
        use xxx; #imports all of the symbols in @EXPORT use xxx (); #imports none of the symbols in @EXPORT #this empty list is the same as: (updated) #BEGIN { require Module } use xxx qw(OpenConnection $LoggedOn_user_id); # imports # all of the symbols in @EXPORT AND subroutine OpenConnection # AND the scalar $LoggedOn_user_id from @EXPORT_OK
        Update: Another attempt at explaining "use".
        Case 1: A plain use xxx; #imports all of the symbols in @EXPORT.

        Case2: use xxx qw(OpenConnection $LoggedOn_user_id); #imports only the function OpenConnection and the scalar $LoggedOn_user_id. Once a list (the parens) after the "use" shows up, this has the effect of making @EXPORT the same as @EXPORT_OK. In other words, the symbols in @EXPORT are not imported by default and must be explicitly imported like the symbols in @EXPORT_OK. Any combination of symbols in @EXPORT or @EXPORT_OK can go in this list after the "use".

        Case 3: (consequence of case 2), use xxx (); There is an empty list of stuff to import and nothing is imported - the automatic importing of the @EXPORT list is "Overridden".

        When you import a symbol, you can use the "short" name, e.g. print $LoggedOn_user_id;. If we "used" the manageusers module, but did not import $LoggedOn_user_id, that variable can still be accessed with the fully qualified name, print $manageusers::LoggedOn_user_id; So if you use the fully qualified name, the variable or sub name does not need to be exported (provided that you have used the module to get it loaded). Only "our" variables can be exported or accessed from another module. A "my" lexical variable cannot be. "our" puts the symbol into the package's symbol table - that means among other things that the fully qualified name is going to work. Such an operation makes no sense for a lexical scope "my" variable.


        #!/usr/bin/perl use warnings; use strict; package manageusers; BEGIN { use vars qw($VERSION @ISA @EXPORT); use DBI; # $ENV{DBI_TRACE}=1; # $ENV{PERL_DBI_DEBUG}=1; require Exporter; @ISA = qw(Exporter); # exported functions our @EXPORT_OK = qw( $attempts $adminaccess $LoggedOn_user_id Now CheckValidLoginChar CheckValidEmailChar print_md5_javascript); $VERSION = '0.0.1'; } our $LoggedOn_user_id=33; our $attempts = 99; 1;
        #!/usr/bin/perl use strict; use warnings; use manageusers qw($LoggedOn_user_id); print "$LoggedOn_user_id\n"; #prints 33 print "$manageusers::attempts \n"; #prints 99 #Note that $attempts is NOT <strike>exported</strike> imported, but still #can be accessed by the fully qualified name!
        I hope this helps. Its really early in the morning here, but I think I did this right. Run my code and then pare further questions down to just the basics and variables involved.

        Corrected "use xx ();" comment. A bit twitchy with the CTL-V this morning. Also changed commend about $attempts in the mail program. Thanks shmem.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1187183]
Approved by GotToBTru
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (8)
As of 2024-06-18 13:37 GMT
Find Nodes?
    Voting Booth?

    No recent polls found

    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.