Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

including variables

by LloydRice (Beadle)
on Feb 16, 2018 at 16:32 UTC ( [id://1209317]=perlquestion: print w/replies, xml ) Need Help??

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

I have a short bit of Perl variable definitions that I would like to use in two different scripts. The simple plan is that I would not need to maintain 2 copies of that fragment. I have tried do, exec, use, module, a few more things. It all seems designed to defeat my simple goal by imposing all of the module structure. As I read the new Camel book, "do" should do what I want. But the variables do not get into the calling script. What am I missing?

Replies are listed 'Best First'.
Re: including variables
by Eily (Monsignor) on Feb 16, 2018 at 16:38 UTC

    all of the module structure
    If you only want to share a variable, the module structure isn't that heavy:
    package MyModule; our $variable = "This variable is visible outside";
    Now with use or require of MyModule, you can access $MyModule::variable. (our actually creates an alias so that $variable points to $MyModule::variable inside the MyModule.pm file).

    Otherwise, if your file only contains the data, and no definition, for example:

    # data.pl { Stuff => 1 }
    You can use do like this: my $data = do "./data.pl"; (ie, the definition of the variable in the calling script, that way each script using the data can define its own name).

    Edit: "./data.pl" is better than "data.pl" because do searches in the folders of @INC, which does not contain the current one by default in perl >= v5.26

Re: including variables
by tinita (Parson) on Feb 16, 2018 at 23:33 UTC
    It might also be worth considering a configuration file. This depends on your variable definitions, of course, but if they don't require to be perl code, an INI/JSON/YAML file could be the better solution.

    If this is not possible, I would probably use a module and let it export a $config hashref. This has the advantage that it's clear in the main code where the variable is coming from.
    use MyConfig qw/ $config /; say $config->{somekey};
    Letting code "import" a number of variables implicitly is usually a bad idea in my experience.
Re: including variables
by karlgoethebier (Abbot) on Feb 17, 2018 at 13:01 UTC

    You might take a look at vars::global. Best regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

    perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help

Re: including variables
by harangzsolt33 (Chaplain) on Feb 16, 2018 at 20:59 UTC
    What would you guys say about this solution?: This file is called : "include.pl"
    use strict; use warnings; include('test.pl') > 2 or die('Couldnt include important file!'); # This sub returns the number of bytes read # or a negative number if there was an error... sub include { my $FILE = shift; -e $FILE or return -1; # File doesn't exist -f $FILE or return -2; # not a plain file my $SIZE = -s $FILE; $SIZE > 2 or return $SIZE; # File is basically empty my $CONTENT; my $F; open $F, '<:raw', $FILE or return -3; # Can't open file binmode $F; sysread($F, $CONTENT, $SIZE) == $SIZE or return -4; # Can't read close $F; eval($CONTENT); return $SIZE; } ShowMessage(); ChangeMessage('Whats up!'); ShowMessage(); exit;
    and this file is called "test.pl" :
    my $MESSAGE = 'Hello World!!!'; # This sub displays the $MESSAGE: sub ShowMessage { print "$MESSAGE\n"; } sub ChangeMessage { $MESSAGE = shift; }

      Note that your sub include appears to essentially be a re-implementation of do.

      Evil low level c style?! If hou gotta have perl data include file do without eval use Safest undumper
Re: including variables
by Anonymous Monk on Feb 17, 2018 at 00:21 UTC

    How about something this?

    #store vars in file dofile.vars: my $var1 = 'foo'; my $var2 = 'bar'; return $var1, $var2; #in your program: my ($var1, $var2) = do "dofile.vars";
Re: including variables
by Anonymous Monk on Feb 17, 2018 at 13:40 UTC
    When I need to share global things, most of all I want it to be maintainable. I put all of the global-things into one module with "getters" and "setters" to access them, and those subs are suspicious, checking for errors such as references to non-existent variables or attempts to set a value to the wrong data-type. I want all of the logic that actually sets or returns these values to occur in only one module – this one – and if something is wrong, anywhere, I want to see an exception being thrown such that I can get a traceback that leads me directly to the source-line where the otherwise-unfindable problem is. There are good CPAN modules to help ... the most obvious one being Moose or any of its lighter-weight cousins.

    I also don't want things to be loaded dynamically, as in do, unless there is a compelling need for it. I literally want to know what the executing source-code consists of at all times, so that I do not have to be concerned whether a particular module had been "done yet" or not.

      Please show us some code demonstrating this approach and the best way to literally know what some Perl source code consists of at all times.

      You don't want to load values dynamically. Well, then why don't you just use the system's environment to store those temporary values? How many values are we talking about and what are you planning to use them for? Anyway, the benefit is that if you have more than one perl program, then one can set the environment variables, and all the other perl programs that run after that will see those values and can easily access them using $ENV{'myvar'} I can't think of an easier solution than that.

      If by accident, you forget to set the environment variables, then your program can easily check to make sure they exist. For example, you could write:

      my $V = exists($ENV{'myvar'}) ? $ENV{'myvar'} : 'default value';

      OR

      exists($ENV{'myvar'}) or die...

        one can set the environment variables

        Not so easy to do. When run a Perl script gets its own copy of the system environment. It can't directly change the system's copy of environment variables so it can't easily set changes that will be seen by other scripts unless they are forked from the parent script (and thus inherit the parent's environment).

        Premature optimization is the root of all job security

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1209317]
Approved by Eily
Front-paged by haukex
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2024-04-18 21:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found