Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedded Perl script in Linux shell [duplicate]

Can I invoke Perl script from Unix shell? For example I have bash script in form like:

#!/bin/sh
echo This is bash

i=12
echo $i

perl <<__HERE__
print "This is perl\n";
my \$i = $i;
print ++\$i . "\n";


echo This is bash again
echo $i

Above is just an example.

Is it possible to pass variables from bash to script? Hope I expressed myself correctly and properly. I need to call Perl script which will take values from bash script and use them and then return processed results.

like image 651
palyxk Avatar asked Sep 12 '25 08:09

palyxk


1 Answers

The problem is the dollar signs need escaped. It makes for an ugly, error prone Perl script. Use environmental variables.

#!/bin/bash

export i=12
readarray results < <(perl <<-'__HERE__'
        my $i = $ENV{'i'};
        print "$i\n";
        $i += 1;
        print "$i\n";
        __HERE__
)
for r in "${results[@]}"; do echo $r; done

The quotes around HERE prevents bash from doing variable substitution. The "-" allows the here is document to be indented it tabs.

While this is a nice exercise in the finer points of Bash, why not just code in Perl or Bash alone? Bash does regular expressions, arrays, etc. And Perl can do everything Bash can.

like image 132
RTLinuxSW Avatar answered Sep 13 '25 21:09

RTLinuxSW