Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Embedding a bash funtion in perl script

by nayabrahil (Novice)
on Oct 21, 2013 at 23:38 UTC ( #1059177=perlquestion: print w/ replies, xml ) Need Help??
nayabrahil has asked for the wisdom of the Perl Monks concerning the following question:

Hello Masters,
I would be glad if someone could tell me how to embed bash function in perl. Also how to call them.
For example:
##function body
function name {
echo "name is nayab rahil"
}


##function call.
name


__________________________________

I am using backtick to run the below function but i always get this error

`function forloop {
for ((a=1;a<=5;a++))
var="$a"
echo "$var"
done
}`

$result=`forloop`;



I want to make a function of the above for loop and run it. Also it should be embedded in perl script only.

Please help!!!

Comment on Embedding a bash funtion in perl script
Re: Embedding a bash funtion in perl script
by choroba (Abbot) on Oct 21, 2013 at 23:53 UTC
    Shell functions cannot be trully embedded into Perl code. There are several reasons why your code does not work:
    1. Function definition must contain parentheses in a shell.
    2. There is a missing do after the for.
    3. There is a missing semicolon after the first backquotes.
    4. The main problem: each backquotes are run in a separate subshell. You cannot define a function in one subshell and run it in a different one (if it is not its subshell).

    You can store the definition in a Perl variable, though, and prepend it to any code that needs to use it (note that backquotes interpolate variables):

    my $f = 'forloop () { for ((a=1;a<=5;a++)) ; do var="$a" echo "$var" done }'; my $result=`$f; forloop`; print $result;

    Nevertheless, usually implementing the whole logic in Perl might get you the clearest code.

    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Embedding a bash funtion in perl script
by keszler (Priest) on Oct 22, 2013 at 07:57 UTC
Re: Embedding a bash funtion in perl script
by nayabrahil (Novice) on Oct 31, 2013 at 11:47 UTC
    Thank You for your explanation. That was helpful.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1059177]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (8)
As of 2014-10-23 00:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (123 votes), past polls