in reply to Re: Heredoc with system call
in thread Heredoc with system call

Sorry for opening an old thread but I arrived to this one as one of my requirements is to also pass arguments to the command as $0 and $1. Can you please suggest how to append this code that it also works with arguments ?
echo "$var1 and $var2 can be read here"; open my $fh, "|-", "sudo su - APP" or die "can't run sudo: $ +?"; print $fh <<' _EOF_'; ls echo "$var1 and $var2 can't be found here ? :( " _EOF_ close $fh;

2019-04-23 Athanasius added code tags

Replies are listed 'Best First'.
Re^3: Heredoc with system call
by bliako (Abbot) on Apr 22, 2019 at 10:26 UTC

    a quick hack is to remove the single quotes from the heredoc marker. In this way the heredoc contents will be processed by perl and any variables within it will be interpolated (and if you do not have use strict; use warnings; all perl-looking variables - declared in your program or not - will be replaced). However, better than a heredoc is to construct a string with your specifications under your full control, using for example, sprintf(), escaping sigils and single quotes. For example, my $var1 = ...; my $str = "echo '$var1' | awk '{print \$1}'";

    See also, Re^2: Ubuntu File Names with spaces and special characters

      Thanks for the suggestion but I am not very familiar with Perl so not really able to comprehend your answer and resolve my case. Basically I have to run a "cp $source $dest" command after logging-in as a different user(ABU) using "sudo su - ABU". The $source and $dest is something that I formulate in my perl script above but I am unable to pass it to the shell command I fork. Code(working snippet): ----
      print "I want to copy $source to $dest after logging-in as ABU"; open my $fh, "|-", "sudo su - ABU" or die "can't run sudo: $?"; print $fh <<_EOF_; echo 'Logged-in as ABU' ls _EOF_ close $fh;
      The only problem is to run "cp $source $dest" on the next line soon after the "ls" command. But I am not sure how to pass these arguments ?

        In the code you just posted you have removed the single-quotes around _EOF_. This will prompt Perl to interpolate any perl-looking variable (for example a word prepended by sigils: $ or @ etc.) within the heredoc content. But now you have none. Try adding, in a new line, echo "i will cp '$source' '$dest'" and see what happens.

        Note: in your posts, please enclose all code within <c> ... </c> tags because most of us in here are humans, not machines.

Re^3: Heredoc with system call
by LanX (Saint) on Apr 22, 2019 at 10:56 UTC
    On bash like systems xargs is supposed to transform STDIN to positionals args

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice