Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I properly run Perl "one liner" command line scripts?

I have looked through a number of tutorials, but I still can't figure out what I am doing wrong... I am trying the code below (in a .pl Perl file, as an executable):

#!/usr/bin/perl

perl -e 'print "Hello";' 

I run this script and get:

Execution of /home/user1/Desktop/file_backups.pl aborted due to compilation errors.

(I'm new to using Perl to call the Linux command line.)

like image 690
Rick Avatar asked Jul 10 '10 17:07

Rick


4 Answers

Try:

#!/usr/bin/perl
# This is a comment ~~~
# This script will be run as a Perl script
# since 'perl' isn't a keyword or function in Perl
# something like this must fail:
#
# perl -e 'print "Hello";' 
#
# The following should work.

print "Hello"; print " World\n";

Or, if you want your shell script to execute Perl code:

#!/bin/sh
# That's a Bash script ~~~
# It's just a command line in a file ...    

perl -e 'print "Hello World";' 

Background: #! is an interpreter directive.

When the command is executed, it is converted to an execution of the interpreter.

like image 119
miku Avatar answered Nov 16 '22 14:11

miku


perl is not a valid command inside a Perl script. If you had named that file as a .sh script, and used #!/bin/bash on the shebang line, it would have worked, but it doesn't really make a lot of sense to write a bash file just to invoke Perl (why not invoke Perl directly?)

Since you mentioned you want to interact with the command line, I'll mention here that you can get at the command line options within Perl via the @ARGV array. (See perldoc perlvar.)

like image 31
Ether Avatar answered Nov 16 '22 16:11

Ether


Just type on the command line (not in a file):

perl -e 'print "Hello World\n";'

This is only really good for one-liners. Longer scripts need their own file.

like image 44
Henno Brandsma Avatar answered Nov 16 '22 16:11

Henno Brandsma


This should work. Double quotes outside single quotes inside ;)

perl -e "print 'Hello'"
like image 8
Slak Avatar answered Nov 16 '22 14:11

Slak