Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

linux - How to call a function (defined in shell script) in a Perl script

I have two scripts, namely shell_script.sh and perl_script.pl.

shell_script.sh : It has function definitions which, when invoked from Perl script, will execute certain commands on Linux in batch mode.

perl_script.pl : It has the code and logic to be implemented, which functions to invoke etc.

The content of shell_script.sh file is as under:

bash-4.2$ cat shell_script.sh
#!/bin/bash

# Function Definitions
func_1 ()
{
  echo "function definition"
}

func_2 ()
{
  echo "function definition"
}

The content of perl_script.pl file is as under:

bash-4.2$ cat perl_script.pl
#!/usr/bin/perl

use Getopt::Long;

my $var1;
my $var1;

GetOptions("var1=s"     => $var1,
       "var2=s" => $var2,
       "help|?" => $help );

if ($help)
{
    HelpMenu();
}

print " Can I call the func_1 (defined in shell script) with arguments here..?? (in this perl script)";

How can i invoke the function func_1() (which is defined in shell_script.sh) in the perl script perl_script.pl ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To invoke a shell function, the shell needs to know its definition. One way to achieve that is to have the shell first source the file which defines the function. And then, without exiting the shell, call the function. From a Perl script, that would be for example:

system 'bash', '-c', 'source shell_script.sh; func_1';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...