Monthly Archives: December 2014

How to Include PHP snippets in WordPress Posts

You can easily include PHP snippets in your WordPress posts by using the PHP Code for Posts plugin available at: https://wordpress.org/plugins/php-code-for-posts/.

It allows you to add your PHP code snippets in a separate dialong in wp-admin and then include a shortcode like I have done here:

servername: jafty.com
54.162.111.61

Here is the same PHP code snippet pasted into this post without using the plugin:

<?php
$servernm = $_SERVER['SERVER_NAME'];
echo "servername: $servernm<br />";//prints 50.xxx.xxx.xxx on adams server

// Function to get the client IP address
function getIP() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$ip = getIP();
echo $ip
?>

CSS Opacity Settings

Here we'll show you how to alter the opacity of an HTML element using the CSS3 opacity property.

Example HTML & CSS Code:

<!DOCTYPE html>
<html>
<head>
<title>320px by 480px</title>
<style>
#iPhoneBox{
width: 320px;
height: 480px;
border:2px solid #333;
background-color: #444;
}

#iPhoneBox img{
opacity: 0.5;
}
</style>
</head>
<body>
<div id="iPhoneBox">
<img src="football.jpg" width="320px" alt="NFL 2015" />
</div><!--/iPhoneBox-->
</body>
</html>

If you take note of the style section on the head part of the above HTML code, you can see that I have made the image have a solid background color. You can experiment with the color used here to give the opaque image different effects. Also experiment with the opacity setting of the image which can be anything between 0 and 1.

How to Use PHP in an External JavaScript File

This is a simple lesson on making your external JavaScript files more dynamic using PHP. PHP is perfectly capable of generating JavaScript code in-line, but have you thought about using it in an external JavaScript file? Well, you can and here's how:

1 - Convert your JavaScript file to a PHP file

Let's say you already have an existing JavaScript file. You'll have to convert it to a PHP file to be able to enjoy all of the goodness of PHP in your JavaScript. All you have to do is change the .js extension to a .php extension so javascript.js becomes javascript.php.

2 - Edit HTML to Include your External JavaScript/PHP File

The next thing you'll do is edit the script tag in your HTML that calls your external JavaScript. It will end up looking like:

<script type="text/javascript" src="javascript.php?c=<?php echo $config_file; ?>"></script>

Notice that two things are changed from how it would look before converting to PHP. First, we added a variable to the file name and second we added a PHP tag to echo the file name of a third file used to hold PHP variables that need to be available to the JavaScript file since the script tag doesn't allow for variables in the including script to be passed to the external JavaScript/PHP file automatically as it would if it were included using a PHP include function. NOTE: the passing of the config script is optional, so if you don't need to pass any PHP variables or functions along in your script tag, all you'd have to do is replace javascript.js with javascript.php and you'd be done. You'll find the method for passing PHP variables and functions will come in handy for many of you tough.

Back to work. Hope this helps.

How to Create a CSS Stylesheet with PHP

Variables can be very useful in CSS. Unfortunately CSS isn't particularly variable-friendly. In comes PHP. It is very easy to dynamically create portions of your CSS style sheet using PHP. You can also generate the entire style sheet using PHP if you wish, but I find it usually more practical to only generate needed sections of my CSS with PHP. Either way, here is how it is done:

Convert Existing CSS Style Sheet to PHP

Lets start with an existing webpage with the below  index.html and style.css files.

Content of index.html:

<!DOCTYPE html>
<html>
<head><title>CSS & PHP Example</title>
<link rel="stylesheet" type="text/css" href="style.php">
</head>
<body>
<div id="box">
<h1>H1 Header</h1>
<p>This is text inside a p tag which is inside of the box div...</p>
</div><!--/#box-->
</body>
</html>

Edit index.html

In index.html, the only required change to convert to a PHP enhanced CSS style sheet is to edit the link tag's href attribute. In our above example HTML code's link tag, we  changed "style.css" to "style.php". For example:

<link rel="stylesheet" type="text/css" href="style.css">

becomes:

<link rel="stylesheet" type="text/css" href="style.php">

That's all for index.html. The rest of the changes will be done in the style sheet.

Content of  style.css

Our original style.css file looks like this:

body{
background-color: #FFFFFF;
}

#box{
position: absolute;
background-color: #0000FF;
border-radius: 15px;
top: 100px;
width: 400px;
height: 300px;
left: 60px;
line-height: 18px;
padding-left: 15px;
padding-right: 12px;
}

Edit style.css File

We will only be making a few minor changes to the above style.css file to make it work with dynamic PHP variables. Here's the simple process:

  • Save style.css as style.php - all we are doing in this step is changing the .css extension to .php.
  • Add some PHP code to the top of the style.php file that changes the content type back to CSS. The php code needed is: <?php header("Content-type: text/css; charset: UTF-8"); ?>
  • Build a couple of variables for various CSS attribute values such as color, padding, height, width etc. You can set any values you wish using PHP by following our example. We are keeping it simple for learning purposes and only changing the background colors in our example webpage by setting a variable for the body's background color and for the box's background color with: <?php $body_bg = "red"; $box_bg = "blue"; ?>
  • Save style.php and upload your two new files, index.html and style.php to your server for testing. Unlike using just HTML and CSS, when you use PHP and HTML files, you can no longer test the webpage from your desktop unless you have an active web server which most people don't. But it will work fine if you upload it to your website and navigate to the index.html page.

Final HTML and PHP Code

I won't list the HTML code again here because it is still the same as it was above, so simply use that if you are following along with this tutorial. The style.php file however has more changes so I am adding the final PHP code for style.php below:

Final PHP/CSS Style Sheet Code

<?php
header("Content-type: text/css; charset: UTF-8");
$body_bg = "red";//"#DBF5F3";
$box_bg = "blue";//"#DBF5F3";
?>

body{
background-color: <?php echo $body_bg; ?>;
}

#box{
position: absolute;
background-color: <?php echo $box_bg; ?>;
border-radius: 15px;
top: 100px;
width: 400px;
height: 300px;
left: 60px;
line-height: 18px;
padding-left: 15px;
padding-right: 12px;
}

The final solution is no more than a blue div with some simple text inside a red body and you can see my working version of it here: http://jafty.com/CSSnPHP/

Converting index.html to index.php

An optional idea which is often more convenient, is to convert your index.html file into a PHP file. All you have to do is change the .html extension to .php and that is done. One good reason why you might want to convert your HTML file to a PHP file is to be able to declare styles in your index.php file too using PHP. You may also want to set your main styles at the top of your index.php script to make them easy to find and edit. The only reason I used an HTML file in my example was to show you the simplest way to use PHP with CSS styles, in the real world, if you're using PHP in your style sheet, you are probably going to want to use it in your index file as well. While it is not a requirement, it does make good sense in many situations.

The one caveat to using PHP variables in both your index.php and you style.php file is that when you use the link tag to include your PHP style sheet as in the above HTML example, the variables do not carry over from one page to the other. One possible fix to this is to create a new file just for configuration settings, I use this to set basic color variables and the like and call it config.php. Then other developers working with your code can very easily change colors, sizes and other styles all in one place without having to pour over all the css code.

Another possible solution to overcoming the passing of variables between index and style scripts is to eliminate the use of the link tag to include the style sheet. You could use a regular PHP include function instead, but you'd have to restructure your style sheet to read like an inline style sheet included in the head section of your index.php page. Basically you would not use the content declaration in PHP and wrap the CSS in <style> and </style> tags instead.

Troubleshooting

If this solution didn't work for you. There's a few possible causes.

If you're on an Apache server and using WordPress with the above solution. You may need leave the file named style.css, and use .htaccess to parse it as PHP. Add the following code to the .htaccess file at the same directory level as the CSS file. Then just use PHP inside it as you would any other PHP file.

<FilesMatch "^.*?style.*?$">
SetHandler php5-script
</FilesMatch>

Another possible WordPress solution involves using PHP code such as:

<?php
 $absolute_path = explode('wp-content', $_SERVER['SCRIPT_FILENAME']);
 $wp_load = $absolute_path[0] . 'wp-load.php';
 require_once($wp_load);

  /*
  Do whatever here...
  */

  header('Content-type: text/css');
  header('Cache-control: must-revalidate');
?>

If your PHP variables are not working as expected. Read above last two paragraphs under the heading "Converting index.html to index.php". There I explain how to overcome this possible issue related to using the HTML link tag.

Summary

There you have it! Easy as pie. Of course, in the real world, you will be developing much more complex solutions than this, but the easy example code here should be just enough to get you started using PHP to generate CSS style sheets. If you have troubles when using WordPress with this solution, the troubleshooting tips should help.

 

 

How to delete lines in Notepad++ that contain specified text string

Have you ever had a list similar to this one:

Some text here...spam...some text here
Some text here...good...some text here
Some text here...good...some text here
Some text here...spam...some text here

...and you wanted to delete all the ones that contained a certain string of characters? If so, I have the solution!

  1. Open the file with the text you want to filter in Notepad++. If you don't have it, google it and download it.
  2. In the top tool bar of Notepad++, click on search/replace to open up the search and replace dialog window.
  3. In the replace dialog window, where it says "find what" enter: .*spam.*
  4. That's dot star then the text or character string you want to search for followed by another dot star. Replace the word "spam" in my example with the text you want to search for.
  5. Check the box towards the bottom left of the replace dialog window that says "Regular Expression" to enable the use of regular expression search mode.
  6. Leave the "Replace with" field blank so it deletes the lines it finds that text in and doesn't replace it with something.
  7. Click "Replace All" to the right of the dialog window and it will replace all lines that contain spam with a blank line.

Here's what your find and replace dialog will look like:

Snap 2014-12-15 at 12.14.49

Delete all blank lines in Notepad++

Now that you have gotten rid of the lines you didn't want, you may also want to delete all those pesky blank lines with another search & replace trick. Here is how:

Simply go back up to the Notepad++ toolbar and navigate to "Edit/Line Operations/Remove Empty Lines" and it will quickly remove any empty lines without having to do a complicated regex which you can also do if you know how.

 

Troubleshoot Email Issues

I generally dread working with email no matter what system it is on! Here I am going to discuss some useful tips for debugging an email system on a Linux server. I am using an Amazon Linux AMI with Centos, but the process is similar for any Linux server you might have. Below I will discuss how to check error files and how to avoid sending email to spam or junk folders.

Having Trouble Sending Email?

If you're emails are not getting through and you don't know why, check your server's log files. Below I'll show you how to find mist email related error logs. They can normally be found in /var/spool/mail/username which on an Amazon Linux distro would be either:

/var/spool/mail/root

or:

/var/spool/mail/ec2-user

It is important to know that in the above context, username, root and ec2-user are files, NOT directories. To open one of those files, navigate to /var/spool/mail like:

cd /var/spool/mail

To open root file with your Linux command line text editor, type:

sudo vi root

...and check the last errors to see the most recent.

TIP: use [shift]+g to skip to the last line of the file using VI editor.

How to Avoid Sending eMail to Spam or Junk Mail folders

I ran several tests to find the best way to send emails from the command line without ending up in the recipient's spam or junk mail folder. Since I was using an Amazon EC2 instance with SES, I will explain the server setup used and then show the results of the tests. Some went to spam immediately and others went straight to the recipient's In Box as it should.

Amazon EC2, SES and sendmail environment

Here are the circumstances that my test cases were executed under:

The following command line commands sent emails to my In Box:

  • /usr/sbin/sendmail linian11@yahoo.com
  • sudo mail linian11@yahoo.com
  • mail linian11@yahoo.com

The following command line commands sent emails to my Spam:

  • /usr/sbin/sendmail -f SESverified@email.com linian11@yahoo.com
  • sudo /usr/sbin/sendmail -f SESverified@email.com linisn11@yahoo.com
  • sudo /usr/sbin/sendmail linian11@yahoo.com

In the above examples, I didn't use parameters for subject, CC or BCC because they don't seem to make any difference. Only  using sendmail, sudo and the -f parameter made a difference to determine if the emails were delivered to my in box or spam folder.

As you can see from the above spam tests, the best way to avoid spam is to:

  • Avoid using the -f parameter even with an SES verified email address.
  • While /usr/sbin/sendmail method did work when avoiding both the -f param and the sudo command, the mail method worked with or without sudo.
  • Either use /usr/sbin/sendmail without -f parameter and without using sudo, or use mail for the best chances of your email getting through to your recipients in boxes.

 

How to use Twitter Boostrap without the Overhead

I went over to the Twitter Bootstrap website today to download the latest Bootstrap version for a new project I am starting and was happy to notice that the Bootstrap files are now available as remotely included files! That means you do not have to download the files and put them on your server. They include the two main files, the CSS and the JavaScript files, for Twitter Bootstrap.

How to use remote file includes for Bootstrap

MaxCDN has provide CDN support for Bootstrap's CSS and JavaScript files. Simply replace old links to CSS and JavaScript files with these Bootstrap CDN links:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

 

 

Subroutines – The Functions of Perl

I used to be foremost a PHP developer. Later, I became a Perl developer. The transition was NOT easy to minimize my experience, but it was tolerable and very interesting. If you love to learn new things, Perl is a great learning experience. I entitled this tutorial "Subroutines, the Functions of Perl" because being a PHP developer first, I was familiar with functions and Perl subroutines act very much like PHP functions. That's just a simple quick way to explain the essence of subroutines to those of you that may know a bit of PHP or even JavaScript or other similar languages that use functions instead.

Perl Subroutine Code Example

As I said, a subroutine is like a function, which is an object and so is a subroutine. It is a way to group together code inside curly brackets and to be able to reuse it later by calling the subroutine similar to the way you would call a function in JavaScript or PHP. Here's an example of a very simple Perl subroutine:

#!/usr/bin/env perl
use strict;
use warnings;
    sub mysubroutine{
    print "This is result of the mysubroutine subroutine...\n";
    }
#Call mysubroutine:
&mysubroutine;

To execute the above code:

  1. save it to a file named test3.pl
  2. use ftp to upload it to a folder on your server
  3. cd to that directory and type "perl test3.pl" at your server command prompt.

Here is the result of running the script:

test3

 

Perl Scalar Variables

Scalar variables are perhaps the most basic and commonly used variables in Perl, so let's learn what they are and how to use them.

Scalar Definition

When I first heard the term "Scalar Variables", my first thought was: "What does Scalar mean? Well maybe some of you already know this, but for those that don't, Scalar, by definition reads something like:

  1. In mathematics, scalar can be a noun or adjective that refers to a quantity consisting of a real number used to measure size or magnitude such as voltage, mass and temperature. The temperature is a scalar quantity.
  2. In Perl, a scalar variable is used to represent a block of information. A scalar may refer to an integer, a float, a string, an object, binary information, etc. It's a versatile variable with no length limit. In Perl code it is preceded by a "$".

Had I even been armed with the above definition I would have been less ignorant, but I had to learn this and now so have you if you didn't already know. I thought this was important. Sorry if you already knew and I'm wasting your time, but please read on!

Perl has three built-in data types: scalars, arrays of scalars, and associative arrays of scalars, known as "hashes".  A scalar is a single string of any size, number, or a reference to something. Normal arrays are ordered lists of scalars indexed by number, starting with 0. Hashes are unordered collections of scalar values indexed by their associated string key.

Scalar variables in Perl use automatic conversion. This means they do not and cannot be declared as a string, number etc. They do that automatically according to content.

Special Perl Variables

Based on usage, special variables in Perl can be classified into the following basic categories. Remember, even special variables are scalar in nature whether they are known by scalar variables, arrays or hashes. Next we list each possible category of Perl special variables:

Global Scalar Special Variables

Here is the list of all the scalar special variables. We have listed corresponding english like names along with the symbolic names.

$_ The default input and pattern-searching space.
$ARG
$. The current input line number of the last filehandle that was read. An explicit close on the filehandle resets the line number.
$NR
$/ The input record separator; newline by default. If set to the null string, it treats blank lines as delimiters.
$RS
$, The output field separator for the print operator.
$OFS
$\ The output record separator for the print operator.
$ORS
$" Like "$," except that it applies to list values interpolated into a double-quoted string (or similar interpreted string). Default is a space.
$LIST_SEPARATOR
$; The subscript separator for multidimensional array emulation. Default is "\034".
$SUBSCRIPT_SEPARATOR
$^L What a format outputs to perform a formfeed. Default is "\f".
$FORMAT_FORMFEED
$: The current set of characters after which a string may be broken to fill continuation fields (starting with ^) in a format. Default is "\n"".
$FORMAT_LINE_BREAK_CHARACTERS
$^A The current value of the write accumulator for format lines.
$ACCUMULATOR
$# Contains the output format for printed numbers (deprecated).
$OFMT
$? The status returned by the last pipe close, backtick (``) command, or system operator.
$CHILD_ERROR
$! If used in a numeric context, yields the current value of the errno variable, identifying the last system call error. If used in a string context, yields the corresponding system error string.
$OS_ERROR or $ERRNO
$@ The Perl syntax error message from the last eval command.
$EVAL_ERROR
$$ The pid of the Perl process running this script.
$PROCESS_ID or $PID
$< The real user ID (uid) of this process.
$REAL_USER_ID or $UID
$> The effective user ID of this process.
$EFFECTIVE_USER_ID or $EUID
$( The real group ID (gid) of this process.
$REAL_GROUP_ID or $GID
$) The effective gid of this process.
$EFFECTIVE_GROUP_ID or $EGID
$0 Contains the name of the file containing the Perl script being executed.
$PROGRAM_NAME
$[ The index of the first element in an array and of the first character in a substring. Default is 0.
$] Returns the version plus patchlevel divided by 1000.
$PERL_VERSION
$^D The current value of the debugging flags.
$DEBUGGING
$^E Extended error message on some platforms.
$EXTENDED_OS_ERROR
$^F The maximum system file descriptor, ordinarily 2.
$SYSTEM_FD_MAX
$^H Contains internal compiler hints enabled by certain pragmatic modules.
$^I The current value of the inplace-edit extension. Use undef to disable inplace editing.
$INPLACE_EDIT
$^M The contents of $M can be used as an emergency memory pool in case Perl dies with an out-of-memory error. Use of $M requires a special compilation of Perl. See the INSTALL document for more information.
$^O Contains the name of the operating system that the current Perl binary was compiled for.
$OSNAME
$^P The internal flag that the debugger clears so that it doesn't debug itself.
$PERLDB
$^T The time at which the script began running, in seconds since the epoch.
$BASETIME
$^W The current value of the warning switch, either true or false.
$WARNING
$^X The name that the Perl binary itself was executed as.
$EXECUTABLE_NAME
$ARGV Contains the name of the current file when reading from .

Global Array Special Variables

@ARGV The array containing the command-line arguments intended for the script.
@INC The array containing the list of places to look for Perl scripts to be evaluated by the do, require, or use constructs.
@F The array into which the input lines are split when the -a command-line switch is given.

Global Hash Special Variables

%INC

The hash containing entries for the filename of each file that has been included via do or require.

%ENV

The hash containing your current environment.

%SIG

The hash used to set signal handlers for various signals.

Global Special Filehandles

ARGV

The special filehandle that iterates over command line filenames in @ARGV. Usually written as the null filehandle in <>.

STDERR

The special filehandle for standard error in any package.

STDIN

The special filehandle for standard input in any package.

STDOUT

The special filehandle for standard output in any package.

DATA

The special filehandle that refers to anything following the __END__ token in the file containing the script. Or, the special filehandle for anything following the __DATA__ token in a required file, as long as you're reading data in the same package __DATA__ was found in.

_ (underscore)

The special filehandle used to cache the information from the last stat, lstat, or file test operator.

Global Special Constants

__END__

Indicates the logical end of your program. Any following text is ignored, but may be read via the DATA filehandle.

__FILE__

Represents the filename at the point in your program where it's used. Not interpolated into strings.

__LINE__

Represents the current line number. Not interpolated into strings.

__PACKAGE__

Represents the current package name at compile time, or undefined if there is no current package. Not interpolated into strings.

Regular Expression Special Variables

$digit

Contains the text matched by the corresponding set of parentheses in the last pattern matched. For example, $1 matches whatever was contained in the first set of parentheses in the previous regular expression.

$&

The string matched by the last successful pattern match.

$MATCH

$`

The string preceding whatever was matched by the last successful pattern match.

$PREMATCH

$'

The string following whatever was matched by the last successful pattern match.

$POSTMATCH

$+

The last bracket matched by the last search pattern. This is useful if you don't know which of a set of alternative patterns was matched. For example: /Version: (.*)|Revision: (.*)/ && ($rev = $+);

$LAST_PAREN_MATCH

Filehandle Special Variables

$|

If set to nonzero, forces an fflush(3) after every write or print on the currently selected output channel.

$OUTPUT_AUTOFLUSH

$%

The current page number of the currently selected output channel.

$FORMAT_PAGE_NUMBER

$=

The current page length (printable lines) of the currently selected output channel. Default is 60.

$FORMAT_LINES_PER_PAGE

$-

The number of lines left on the page of the currently selected output channel.

$FORMAT_LINES_LEFT

$~

The name of the current report format for the currently selected output channel. Default is the name of the filehandle.

$FORMAT_NAME

$^

The name of the current top-of-page format for the currently selected output channel. Default is the name of the filehandle with _TOP appended.

$FORMAT_TOP_NAME

Understanding Perl Variables and Arguments

This is my third tutorial in the Perl tutorial series. This Perl tutorial will demonstrate how to use basic variables and command line arguments in a simple Perl script.

Prerequisites

If you don't have Perl installed yet or haven't done the hello world tutorial, here are their respective links since the information is vital to successfully competing this tutorial if you are new to Perl:

Getting Started with Perl(installing Perl)

Writing Your First Perl Script(hello world)

Declaring Perl Variables

I recall my first day using Perl. I tried to use variables like I normally would in PHP, like:

$var_name = "some value";

Well, that doesn't work in Perl. You'll get an error that says something like "perl global symbol requires explicit package name at..." Variables in Perl need to be declared with "my" like this:

my $var_name = "some value";

That works without throwing the previous error.

Using Perl Command Line Arguments

Commend line arguments are values passed to a Perl script that are used in some fashion within the code. Name, File name, path, phone no. and URL are some possible examples of arguments often passed to to a Perl script via the command line.  For the purposes of this tutorial we are just going to pass two simple words, one and two to the script and print them to the screen with Perl code. We will name our script test1.pl and this is how it will be called passing "one" and "two" as arguments. Type this at the command prompt in your shell:

perl test1.pl one two

The ARGV Array

Perl command line arguments are neatly packaged up for us in the ARGV array and can be accessed like this:

the first command line parameter in our example was "one" and it can be accessed like the following example using the $ARGV[0] line:

my $arg1=$ARGV[0];

...and the second argument passed, "two", would be accessed using:

my $arg2=$ARGV[1];

Notice that, just like in PHP and other popular languages, the arrays start at 0 so the first argument is identified with 0 and the second with 1.

Let's put together what we've learned here into a working script called test1.pl. Here are its contents:

#!/usr/bin/perl
#Perl Script to demo variables and arguments
# Strict and warnings are normally recommended.
use strict;
use warnings;

#arguments = dict file & word string
my $arg1=$ARGV[0];
my $arg2=$ARGV[1];
# Print a message.
print "argument 1: $arg1\n";
print "argument 2: $arg2\n";

Use a simple text editor such as notepad and copy the above code to a blank file and save it as "test1.pl". Upload test1.pl via FTP and open a command prompt to to your server. Change to the directory where you uploaded the test1.pl file and type at the command prompt:

perl test1.pl one two

...or perl test1.pl followed by any two words you wish to pass to the script and see printed to the screen. Running the script above produced:

test1

Summary

As you can see from our image, executing our test1.pl script will product:

argument 1: one

argument 2: two

Hopefully you now understand how to use simple variables and command line arguments with Perl now. Be sure to read my next tutorial to learn more! Check out Perl Scalar Variables to learn more about basic Perl variables

 

Writing your First Perl Script

This simple Perl tutorial will demonstrate how you can write, install and run your first Perl script. First, you need to be sure you have Perl installed and install it if needed. To check for Perl and install as needed, see my first Perl tutorial, Getting Started with Perl for instructions on checking for and installing Perl and it's dependencies.

Perl Hello World Script

As the long time tradition of learning code dictates, we'll start out with the simplest of Perl Scripts, the hello.pl file. Copy and paste or type the following content into a new document using notepad, notepad++ or another very simple word editor. Do not use a complex one such as MS Word as it includes unseen characters that will mess your code up. Without further delay, here is the Perl hello.pl file:

#!/usr/bin/perl
#Perl Hello World Script
# Strict and warnings are normally recommended.
use strict;
use warnings;
# Print a message.
print "Hello, World!\n";

Run your First Perl Script

Save the above example code in a file named hello.pl and upload it to a directory you can easily find and access via a command prompt or shell on your server. I upload my Perl scripts to /home/ec2-user which is the default directory on an Amazon Linux server when logging in as ec2-user, but any directory will work if it is given permission. Follow these few simple instructions to upload and run hello.pl:

  1. Use an FTP client such as Filezilla to upload your hello.pl file
  2. Use Putty to open a shell command prompt and change to the directory you uploaded hello.pl to using the cd /path/directory command.
  3. Once in the same directory as the hello.pl file, you can simply type "perl hello.pl" at the command line and it will execute your script. Congratulations! You just ran your first Perl script. Happy coding!

Here is what it looks like when you run the hello.pl script as described above:

hello

Summary

As you can see, all it does is prints "Hello, World!" to the screen on the next line in your shell. Not much, but it's a great first step to learning Perl. Now you should have Perl installed(see Installing Perl) and know how to create and execute a simple Perl script.

Getting Started with Perl

Perl is an advanced programing language with over 26 years of development behind its belt, so I have decided to take it seriously and provide Perl tutorials on Jafty.com starting at the beginner level and progressing through more advanced Perl programming techniques.

Beginning with Perl

Perl does have different versions, but to keep it simple, we are going with the more popular stable version 5 of Perl. There is a version 6 of Perl, but it is a different language that is not yet as widely supported as version 5. Version 6 may have its own use cases that differ from version 5, but for most people's needs, version 5 is currently preferred and probably will be for some time. That's not saying that you shouldn't check out version 6 also, just try version 5 first is what I am recommending for simplicities sake alone. There is also a version 4 that is quite outdated an no longer considered for serious new development use. Type "perl --version" at a command prompt to find out what version you have or read on for more detailed information.

Let's get started by installing Perl. If you already have Perl installed, you may skip to the next tutorial, Writing your first Perl script. If you are not sure, read on and we will show you how to find out. Here is the basic process:

  1. check to see if Perl is installed. If it is, you can skip the rest of this tutorial and move on to writing your first Perl script.
  2. Check if gcc compiler is installed and if it is not, this is typically installed first. The other option is to install gcc and Perl simultaneously which we will get into later in this tutorial.
  3. Install Perl and gcc as needed.
  4. Write your first Perl script to test Perl.

How to Check for Perl Installation

Before you proceed to install Perl, you should make sure you don't already have it because many servers come with it. The easiest way to check for Perl is to type "perl -v" at your command prompt from a shell console window. Here are example results if you do have it already:
[ec2-user@ip-172-30-0-9 ~]$ perl -v

This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-thread-multi
(with 25 registered patches, see perl -V for more detail)

Copyright 1987-2012, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

The first line above is the command prompt with only "perl -v" typed after it and the remaining lines are the response on a server with Perl 5 installed and working.

How to Install Perl

Here is a brief guide on installing latest stable version of Perl 5 on a Centos, Red Hat, Linux server. I did it on an Amazon cloud server, but the process is the same on any similar Linux flavor that supports YUM.

Check for GCC

As always before installing something on your server, check to make sure it is not installed already. I am always surprised to find something on my server that I didn't know was there, but it does happen quite frequently. In the following example, the first line contains the command prompt followed by the command to check for the gcc compiler which is "gcc --version". The remaining lines in brown text are the result of the gcc --version command in cases where gcc does exist on the server already:
[ec2-user@ip-172-30-0-9 ~]$ gcc --version
gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-16)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

If you did not get a similar response, then you need to install gcc for sure and most likely Perl too, so read on!

Installing a Developer Package using YUM

The easy way to get gcc and alot of other useful developer tools is to use YUM to install a group of software known as the Yum Developer Tools group. Available groups in Yum can be shown at the command line by typing "yum group list". Here are actual results from my server:

developerIn the above screenshot the Developer Tools group has already been installed. If you run this now before doing the install, Developer Tools will be listed under the "available groups" heading instead of the "installed groups" as you see here.

Installing gcc with Developer Tools is my recommendation because it could save you from installing other needed tools later. To install the Developer Tools group now, simply type this command into your shell:

sudo yum group install "Development Tools"

If for that didn't work, I've heard that on some servers, you have to use yum groupinstall without the space. If the above failed use this:

sudo yum groupinstall "Development Tools"

Now if you type "gcc --version" you should see that gcc is installed!

Installing gcc by Itself

This method may be simpler to do, but doesn't give you other useful tools a developer is likely to use. If you opt to simply install gcc quick and easy, just type this at the command prompt and you're done:

yum install gcc*

That will install and update all necessary dependencies.

Install Perl

Now that you are sure to have gcc C compiler installed, it's time to install Perl. The quick and easy way is to type this at the command prompt:

sudo yum install perl

If that doesn't work, check out the other ways to install Perl using these links as it is a bit much to put here:

http://learn.perl.org/installing/unix_linux.html

or this one:

http://learnperl.scratchcomputing.com/install/

Summary

Once you have made it to the end of this tutorial, you will have Perl up and running on your server. Now it is time to Write your first Perl script, so go here and do it now: http://jafty.com/blog/writing-your-first-perl-script/