Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Running blocks of shell script from within perl script

by Tanktalus (Canon)
on Apr 22, 2014 at 22:20 UTC ( [id://1083240]=note: print w/replies, xml ) Need Help??


in reply to Running blocks of shell script from within perl script

You have a few choices, as always.

The simplest solution, the one more or less given by others, and the one I've been using, is to simply put the script in an external file, and run it. In my case, I just create a scripts subdirectory and run from there. The script is not embedded in my perl code. (I do have a lot of code to genericise this, including ensuring permissions, copying to remote filesystems, etc.)

However, it's not the only solution. If it's important to keep the code and its metadata together, which is understandable, there are a couple more options I can think of.

The first is to try to parse the first line of the CHECK_CODE directly, and if it looks like a shell, to use it with a "-c" flag to run the rest. This is not only non-trivial, but error prone. However, if you can pull it off, it requires no change to your existing data. You'd eventually be left with something like:

my ($shell, $code) = mystical_extraction_goes_here($check{CHECK_CODE}) +; open my $fh, '-|', $shell, -c => $code or die "Can't run shell $shell: + $!"; my @return = <$fh>; close $fh;

The second is to have the data do this for you. Have the shell, its options (including the -c), and the script, in your data. I don't know the original format of the data, but I'd suggest you'd end up with keys such as SHELL, SH_OPTS, and CHECK_CODE. And maybe CODE_OPTS. The _OPTS would be arrays. And then you'd get code like this:

my @cmd = $check{SHELL}; if (exists $check{SH_OPTS}) { push @cmd, ref $check{SH_OPTS} eq 'ARRAY' ? @{$check{SH_OPTS}} : $ch +eck{SH_OPTS}; } push @cmd, $check{CHECK_CODE}; if (exists $check{CODE_OPTS}) { push @cmd, ref $check{CODE_OPTS} eq 'ARRAY' ? @{$check{CODE_OPTS}} : + $check{CODE_OPTS}; } open my $fh, '-|', @cmd or die "Can't run check code: $!"; #...
What makes this solution cool is that a) you don't have to write a bunch of ugly guesses as to potential shells the next guy might want to use, and b) you allow that person to use other "shells". Like awk. Or sed. Or even perl. No limitation to just sh-compatible shells with the -c flag.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1083240]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-24 02:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found