Can I run a Perl script from stdin?

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.


perl mytest.pl 

should be the correct way. Why are you doing the unnecessary?


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

Tags:

Perl