I've found it handy to be able to neatly encapsulate sh/bash shell scripts in here documents passed to system() as follows:

#! /usr/bin/perl sub whatever { system <<'SCRIPT'; date echo "what about this?" SCRIPT } whatever;

However, I've not been able to find a syntax that allows passing arguments to the shell script in the here document. I've been able to sort of work around it by passing environment variables like this:

#! /usr/bin/perl my $value = "testvalue"; sub whatever { system "MYVAR=$value;" . <<'SCRIPT'; date echo "arg1($MYVAR)" echo "what about this?" SCRIPT } whatever;

But that's unsatisfying. What I really want is to pass positional arguments to the scripts, and reference them via the likes of $* or $1 within the embedded shell script As Usual.

<LATER...>

The following ALMOST works (nods to Murphy's Law), except for the fact that the first argument winds up in $0 instead $1..... ugh....

#! /usr/bin/perl my $rc = system ("sh", "-c", <<'SCRIPT', "one", "two", "three"); echo 'this is a test' echo 'again' echo "0($0) 1($1) 2($2)" SCRIPT $rc >> 8; exit $rc;
<LATER STILL...>

Um, DUH! The above technique works fine if a pass a dummy program name argument first.....

#! /usr/bin/perl my $rc = system ("sh", "-c", <<'SCRIPT', "bogus_program_name", "one", +"two", "three"); echo 'this is a test' echo 'again' echo "0($0) 1($1) 2($2) 3($3)" SCRIPT $rc >> 8; exit $rc;

In reply to passing arguments to a shell script in a here document passed to system() ? by jethrick

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.