Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Perl scripts from a file in linux

Tags:

file

perl

I'm in Linux (CentOS) trying to run a basic Perl script from a file. I am getting an error. I think it has something to do with the syntax, but I can't figure it out.

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

This runs fine and will print Hello World on the next line. However, when I put this into vi and save it as perlOne, exactly the same (perl -e 'print "Hello World\n";') and run the command:

$ perl perlOne

I get the error: "syntax error at perlOne line 1, near "perl -e -- Execution of perlOne aborted due to compilation errors."

It's the same line, but it does not work in the file.

I'm working through the Perl tutorial from Linux Pro Magazine - which is where I got this from.

like image 769
Scott_Lew Avatar asked Jun 17 '13 02:06

Scott_Lew


People also ask

How do I run a Perl script from Unix command line?

at the top of your perl script, mark the script as executable with the UNIX chmod command, and execute the perl program by simply typing its name at a UNIX prompt.


1 Answers

The command-line switch -e allows you to run code from the command line, instead of having to write your program to a file and then execute it.

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

Output:

Hello World

If you want to run it from your file you will need to write it differently:

#!/usr/bin/perl

use strict;
use warnings;

my $message = 'Hello World';
print $message . "\n";

# You can also make it directly
print "Hello World\n";

While I do not recommend it can also be written as:

print "Hello World\n";
like image 62
Prix Avatar answered Oct 13 '22 20:10

Prix