0

I want to convert a shell script code in Perl and use exec to execute the code. I have program written in perl but on a condition i have to add a code which i know how we can do in shell script but not sure how we can do in perl.

Shell Script Code:

(
echo "MIME-Version: 1.0"
echo "Subject: "
echo "Content-Type: text/html"
cat <emailbody>
) | mailx -r "[email protected]" 

My Perl Code:

!/usr/bin/perl

use strict;
use warnings;

my $mailx = "/usr/bin/mailx";

if($ARGV[0] eq "ty" && $ARG[1]){
 /// Here we want to use the shell script code .
}

my @args_to_pass = ($mailx, @ARGV);
exec @args_to_pass;
6
  • 1
    There are a number of Perl modules for sending emails that you could use. Search around on metacpan for one that looks good. Commented Aug 1, 2019 at 2:30
  • @Shawn i know that. But i have some restriction under which i have to use this Commented Aug 1, 2019 at 2:32
  • Various versions of mailx exist, which differ (a lot) in how to specify headers. Even sendmail is better (more consistent) -- can you use that instead? Commented Aug 1, 2019 at 4:36
  • @Developer : If you want to handle everything in shell, write it as a shell script, and invoke your script from your Perl application. This also makes debugging easier. Commented Aug 1, 2019 at 7:14
  • 1
    "sendmail is also a good option" --- then how's this post, for example? Something I could find readily. There's a lot more on SO. Commented Aug 1, 2019 at 16:31

1 Answer 1

3

A somewhat literal translation of your shell code would be:

if($ARGV[0] eq "ty" && $ARG[1]){
    my $pid = open(STDIN, '-|') // die "Can't fork(): $!";
    if ($pid == 0) {
        print "MIME-Version: 1.0\n";
        print "Subject: \n";
        print "Content-Type: text/html\n";

        exec 'cat', ... or die "Can't exec() cat: $!";
        # or print more text, but don't forget to exit() afterwards if you don't exec
    }
}

The idea is to create a pipe and a subprocess. Using open as shown above does that, with the write end of the pipe connected to the child's STDOUT and the read end connected to the parent's STDIN.

The child process then writes data to the pipe and exits. It can do all the work by itself and exit, or exec into cat at the end.

All of the output produced by the child is available on the parent's STDIN, which is inherited by mailx.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.