How to share/export a global variable between two different perl scripts?

前端 未结 3 1456
你的背包
你的背包 2020-12-14 07:08

How do we share or export a global variable between two different perl scripts.

Here is the situation:

first.pl

#!/usr/bin/         


        
相关标签:
3条回答
  • 2020-12-14 07:59

    Cant you use package and export the variable?

    0 讨论(0)
  • 2020-12-14 08:04

    In general, when you are working with multiple files, and importing variables or subroutines between them, you will find that requiring files ends up getting a bit complicated as your project grows. This is due to everything sharing a common namespace, but with some variables declared in some files but not others.

    The usual way this is resolved in Perl is to create modules, and then import from those modules. In this case:

    #!/usr/bin/perl
    
    package My::Module;  # saved as My/Module.pm
    use strict;
    use warnings;
    
    use Exporter;
    our @ISA = 'Exporter';
    our @EXPORT = qw(@a @b);
    
    our (@a, @b);
    
    @a = 1..3;
    @b = "a".."c";
    

    and then to use the module:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use My::Module;  # imports / declares the two variables
    
    print @a;
    print @b;
    

    That use line actually means:

    BEGIN {
        require "My/Module.pm";
        My::Module->import();
    }
    

    The import method comes from Exporter. When it is called, it will export the variables in the @EXPORT array into the calling code.

    Looking at the documentation for Exporter and perlmod should give you a starting point.

    0 讨论(0)
  • 2020-12-14 08:10

    They will share global variables, yes. Are you seeing some problem with that?

    Example:

    first.pl:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    our (@a, @b);
    
    @a = 1..3;
    @b = "a".."c";
    

    second.pl:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    require "first.pl";
    
    our (@a,@b);
    print @a;
    print @b;
    

    Giving:

    $ perl second.pl
    123abc
    
    0 讨论(0)
提交回复
热议问题