Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Using require

by kidd (Curate)
on Jul 10, 2002 at 16:47 UTC ( #180795=perlquestion: print w/ replies, xml ) Need Help??
kidd has asked for the wisdom of the Perl Monks concerning the following question:

I started using strict not so long ago, and now Im in front of a problem. When I create my scripts I like to make a config.pl so it would be the only thing a user changes(settings, option, that kind of things)...

So yesterday I made the first script this way, only that this time I used strict and -w...

I created my config.pl and added the require line, I test it and oopss...I don't seem to be using the variables inside config...

Could someone give me some light and tell me why it isnt working that way...here is some example...

Let's say I have my "config.pl" with a variable:

#!/usr/bin/perl -w use strict; my $option = 1;

And my main code is like this:

#!/usr/bin/perl -w use strict; require "config.pl" print "Option = 1" if $option != 0;

For some reason $option is not "imported" from config.pl and I can't explain why...thanks

Comment on Using require
Select or Download Code
Re: Using require
by Abigail-II (Bishop) on Jul 10, 2002 at 16:56 UTC
    $option is a lexical variable inside config.pl. A file is a lexical scope. Make $option a package variable.

    Abigail

      How do I create $option a package?
        By not creating it a lexical variable. Leave the my off. Of course, you either have to get rid of the strictness, use use vars, or use a fully qualified name.

        Abigail

Re: Using require
by perrin (Chancellor) on Jul 10, 2002 at 17:16 UTC
    package MyConfig; use strict; use vars qw($option); $option = 1;
    Then, elsewhere:

    use MyConfig; print "Option = 1" if $MyConfig::option != 0;
      Thanks Abigail and thanks Perrin a lot...I created config.pl a package, and it worked great...

      It's good to learn something new...I read the documentation on use vars and now I know what is that Im doing wrong....THANKS

Re: Using require
by zentara (Archbishop) on Jul 11, 2002 at 17:07 UTC
    Use 'our'.
    Let's say I have my "config" with a variable:

    our $option = 1;
    1; #must end with true return
    And my main code is like this: #!/usr/bin/perl -w use strict; our $option require "./config.pl" print "Option = 1" if $option != 0;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://180795]
Approved by ichimunki
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2014-09-22 07:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (182 votes), past polls