如何从shell脚本调用Perl函数?

时间:2021-09-04 07:13:21

I have written a library in Perl that contains a certain function, that returns information about a server as a character string. Can I call this function from a shell directly?

我在Perl中编写了一个包含某个函数的库,它将有关服务器的信息作为字符串返回。我可以直接从shell调用此函数吗?

My boss asks "Can you call it from a shell directly for the time being?" Because he said that, I think I should be able to do it, but how do I do it?

我的老板问:“你能暂时直接从外壳打电话吗?”因为他说,我认为我应该能够做到,但我该怎么做呢?

2 个解决方案

#1


perl -MServerlib=server_information -e 'print server_information()'

Is another way to do this, but only if Serverlib exports server_information sub. If it doesn't, you would need to do the below instead:

是另一种方法,但只有当Serverlib导出server_information sub时。如果没有,则需要执行以下操作:

perl -MServerlib -e 'print MServerlib::server_information()'

#2


As perl's command line arguments are a bit inscrutable, I'd wrap it in a simpler perl script that calls the function. For example, create a script serverinfo which contains:

由于perl的命令行参数有点难以理解,我将它包装在一个更简单的调用函数的perl脚本中。例如,创建一个脚本serverinfo,其中包含:

#!/usr/bin/perl

require 'library.pl';
say library::getServerInformation();

then run:

chmod u+x serverinfo

The advantage of doing it this way is the output and arguments of the script can be corrected if the function itself changes. A command line script like this can be thought of as an API, which shouldn't change when the implementation changes.

这样做的好处是,如果函数本身发生变化,脚本的输出和参数可以得到纠正。像这样的命令行脚本可以被认为是一个API,在实现更改时不应该更改。

#1


perl -MServerlib=server_information -e 'print server_information()'

Is another way to do this, but only if Serverlib exports server_information sub. If it doesn't, you would need to do the below instead:

是另一种方法,但只有当Serverlib导出server_information sub时。如果没有,则需要执行以下操作:

perl -MServerlib -e 'print MServerlib::server_information()'

#2


As perl's command line arguments are a bit inscrutable, I'd wrap it in a simpler perl script that calls the function. For example, create a script serverinfo which contains:

由于perl的命令行参数有点难以理解,我将它包装在一个更简单的调用函数的perl脚本中。例如,创建一个脚本serverinfo,其中包含:

#!/usr/bin/perl

require 'library.pl';
say library::getServerInformation();

then run:

chmod u+x serverinfo

The advantage of doing it this way is the output and arguments of the script can be corrected if the function itself changes. A command line script like this can be thought of as an API, which shouldn't change when the implementation changes.

这样做的好处是,如果函数本身发生变化,脚本的输出和参数可以得到纠正。像这样的命令行脚本可以被认为是一个API,在实现更改时不应该更改。