How can I get one Perl script to see variables in

2020-07-06 05:44发布

I have a Perl script that is getting big, so I want to break it out into multiple scripts. namely, I want to take out some large hash declarations and put them into another file. How do I get the original script to be able to see and use the variables that are now being declared in the other script?

This is driving me nuts because I haven't used Perl in a while and for the life of me can't figure this out

标签: perl
4条回答
相关推荐>>
2楼-- · 2020-07-06 05:44

Yet another suggestion to use a module.

Modules are not hard to write or use. They just seem hard until you write one. After the first time, it will be easy. Many, many good things come from using modules--encapsulation, ease of testing, and easy code reuse to name a few.

See my answer to a similar question for an example module, with exported functions.

Also, some very smart people in the Perl community like modules so much that they advocate writing apps as modules--they call them modulinos. The technique works well.

So, in conclusion, try writing a module today!

查看更多
看我几分像从前
3楼-- · 2020-07-06 05:45

You use modules. Or modulinos.

Make it a module that exports (optionally!) some variables or functions. Look up how to use the Exporter module.

查看更多
做个烂人
4楼-- · 2020-07-06 05:52

Use a module:

package Literature;

our %Sidekick = (
  Batman => "Robin",
  Bert   => "Ernie",
  Don    => "Sancho",
);

1;

For example:

#! /usr/bin/perl

use Literature;

foreach my $name (keys %Literature::Sidekick) {
  print "$name => $Literature::Sidekick{$name}\n";
}

Output:

$ ./prog 
Bert => Ernie
Batman => Robin
Don => Sancho
查看更多
来,给爷笑一个
5楼-- · 2020-07-06 05:59

As an addition to the other "use a module" suggestions, if you plan on reusing the module a lot, you will want to get this installed into either your site library (usually under ...(perl install folder)...\site\lib.

If not (perhaps, it has limited reusability outside the script), you can keep it in the directory with your script and import it like so:

use lib './lib'; # where ./lib is replaced with wherever the module actually is.
use MyModule;
查看更多
登录 后发表回答