Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I run a Perl script from stdin?

Tags:

perl

Suppose I have a Perl script, namely mytest.pl. Can I run it by something like cat mytest.pl | perl -e?

The reason I want to do this is that I have a encrypted perl script and I can decrypt it in my c program and I want to run it in my c program. I don't want to write the decrypted script back to harddisk due to secruity concerns, so I need to run this perl script on-the-fly, all in memory.

This question has nothing to do with the cat command, I just want to know how to feed perl script to stdin, and let perl interpreter to run it.

like image 797
solotim Avatar asked Oct 14 '09 10:10

solotim


2 Answers

perl < mytest.pl 

should do the trick in any shell. It invokes perl and feeds the script in via the shell redirection operator <.

As pointed out, though, it seems a little unnecessary. Why not start the script with

#!/usr/bin/perl

or perhaps

#!/usr/bin/env perl

? (modified to reflect your Perl and/or env path)

Note the Useless Use of Cat Award. Whenever I use cat I stop and think whether the shell can provide this functionality for me instead.

like image 85
Brian Agnew Avatar answered Sep 20 '22 12:09

Brian Agnew


Sometimes one needs to execute a perl script and pass it an argument. The STDIN construction perl input_file.txt < script.pl won't work. Using the tip from How to assign a heredoc value to a variable in Bash we overcome this by using a "here-script":

#!/bin/bash
read -r -d '' SCRIPT <<'EOS'
$total = 0;

while (<>) {
    chomp;
    @line = split "\t";
    $total++;
}

print "Total: $total\n"; 
EOS

perl -e "$SCRIPT" input_file.txt
like image 22
dma_k Avatar answered Sep 22 '22 12:09

dma_k