Bob
Bob

Reputation: 33

Run Perl Script From Unix Shell Script

Hi I have a Unix Shell Script call Food.sh ; I have a Perl Script call Track.pl. Is there a way where I can put Track.pl's code in to Food.sh code and still have it work ? Track.pl requires one arugement to label a name of a folder.

Basically it will run like this.

Unix Shell Script codes RUN

step into 

Perl Script codes RUN
Put in name of folder for Perl script
Rest of script runs

exit out.

Upvotes: 2

Views: 6068

Answers (2)

ikegami
ikegami

Reputation: 386561

You have a few options.

  1. You can pass the code to Perl using -e/-E.

     ...
     perl -e'
    
        print "Hello, World!\n";
    
     '
     ...
    

    Con: Escaping can be a pain.[1]

  2. You can pass the code via STDIN.

     ...
     perl <<'END_OF_PERL'
    
        print "Hello, World!\n";
    
     END_OF_PERL
     ...
    

    Con: The script can't use STDIN.

  3. You can create a virtual file.

     ...
     perl <(
     cat <<'END_OF_PERL'
    
        print "Hello, World!\n";
    
     END_OF_PERL
     )
     ...
    

    Con: Wordy.

  4. You can take advantage of perl's -x option.

     ...
     perl -x -- "$0"
     ...
     exit
    
     #!perl
     print "Hello, World!\n";
    

    Con: Can only have one snippet.

    $0 is the path to the shell script being executed. It's passed to perl as the program to run. The -x tells Perl to start executing at the #!perl line rather than the first line.

Ref: perlrun


  1. Instances of ' in the program needs to escaped using '\''.

    You could also rewrite the program to avoid using '. For example, you could use double-quoted string literals instead of single-quoted string literals. Or replace the delimiter of single-quoted string literals (e.g. q{...} instead of '...'). As for single-quoted inside of double-quoted and regex literals, these can be replaced with \x27, which you might find nicer than '\''.

Upvotes: 14

perlpilot
perlpilot

Reputation: 101

(I'm assuming your goal is just to have all of the code in a single file so that you don't have multiple files to install)

Sure, there's a way to do this, but it's cumbersome. You might want to consider converting the shell script entirely to Perl (or the Perl script entirely to shell).

So ... A way to do this might be:

#!/bin/sh

echo "shell"

perl -E '
say "perl with arg=$ARGV[0]"
' fred

echo "shell again"

Of course, you'd have to be careful with your quotes within the Perl part of the program.

You might also be able to use a heredoc for the Perl part to avoid quoting issues, but I'm not sure about that.

Upvotes: 1

Related Questions