freddiefujiwara
freddiefujiwara

Reputation: 59079

How can I call a Perl function from a shell script?

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?

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?

Upvotes: 4

Views: 4281

Answers (2)

Mark
Mark

Reputation: 6306

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:

#!/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.

Upvotes: 7

Axeman
Axeman

Reputation: 29854

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:

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

Upvotes: 10

Related Questions