You are on page 1of 6

Introduction to Perl

Use some simple text editor to create a file.


print "Hello, world!\n";

You can save that program under any name you wish. Perl doesnt require any special kind of filename or extension. Let's save the file as script.pl Run Command Prompt and make sure you're working in a directory where you saved the script.pl file. To run the script, type perl [scriptname]
perl script.pl

Instead of print, in Perl 5.10 or later we can use "say", which does almost the same thing, but with less typing. It adds the newline for us, meaning that we can save some time forgetting to add it ourselves
use 5.010; say "Hello World!"; # it's the second script

We include a "use 5.010" statement that tells Perl that we used new features
perl script.pl

This program only runs under Perl 5.10 or later. Perl generally lets you use insignificant whitespace (like spaces, tabs, and newlines) at will to make your program easier to read. Comments also make a program easier to read. In Perl, comments run from a pound sign (#) to the end of the line. There are no block comments in Perl.

Numeric literals
255 255.0 8.25e25 7.5e23 12e24 50_155_128 literals # # # # # # integer literal floating-point literal 8.25 times 10 to the 25th power negative 7.5 times 10 to the 23th negative 12 times 10 to the 24th perl allows you to add underscores for clarity within integer

http://www.learn-with-video-tutorials.com/perl-tutorial-video

Perl allows you to specify numbers in other ways than base 10 (decimal). Octal (base 8) literals start with a leading 0, hexadecimal (base 16) literals start with a leading 0x, and binary (base 2) literals start with a leading 0b.# The hex digits A through F (or a through f) represent the conventional digit values of 10 through 15
0377 # 377 octal, same as 255 decimal 0xff # FF hex, also 255 decimal 0b11111111 # also 255 decimal

String literals
Perl has full support for Unicode, and your string can contain any of the valid Unicode characters. However, because of Perls history, it doesnt automatically interpret your source code as Unicode. If you want to use Unicode literally in your program, you need to add the utf8 pragma
use utf8;

The single quotes are not part of the string itselftheyre just there to let Perl identify the beginning and the ending of the string. Any character other than a single quote or a backslash between the quote marks (including newline characters, if the string continues on to successive lines) stands for itself inside a string. To get a backslash, put two backslashes in a row, and to get a single quote, put a backslash followed by a single quote
'hello' # five characters 'Don\'t let an apostrophe end this string prematurely!' 'the last character is a backslash: \\' 'hello\n' # hello followed by backslash followed by n 'hello there' # hello, newline, there (11 characters total)

Note that Perl does not interpret the \n within a single-quoted string as a newline, but as the two characters backslash and n. Only when the backslash is followed by another backslash or a single quote does it have special meaning A double-quoted string literal is a sequence of characters, although this time enclosed in double quotes. But now the backslash takes on its full power to specify certain control characters, or even any character at all through octal and hex representations
"hello world\n" # hello world, and a newline "coke\tsprite" # coke, a tab, and sprite

The backslash can precede many different characters to mean different things (generally called a backslash escape). For example: \n Newline \r Return \t Tab \l Lowercase next letter \L Lowercase all following letters until \E \u Uppercase next letter http://www.learn-with-video-tutorials.com/perl-tutorial-video

\U Uppercase all following letters until \E \e Escape (ASCII escape character) \007 Any octal ASCII value (here, 007 = bell) \x7f Any hex ASCII value (here, 7f = delete) \x{2744} Any hex Unicode code point (here, U+2744 = snowflake) \cC A control character (here, Ctrl-C) You can concatenate, or join, string values with the dot operator
"hello" . "world" "hello" . ' ' . "world" # same as "helloworld" # same as 'hello world'

A special string operator is the string repetition operator, consisting of the single lowercase letter x. This operator takes its left operand (a string) and makes as many concatenated copies of that string as indicated by its right operand (a number).
"fred" x 3 # is "fredfredfred" 5 x 4 # "5" x 4, which is "5555"

Perl automatically converts between numbers and strings as needed.

Scalar Variables
Variable names begin with a dollar sign, called the sigil, followed by a Perl identifier: a letter or underscore, and then possibly more letters, or digits, or underscores. Another way to think of it is that its made up of alphanumerics and underscores, but cant start with a digit. Perl uses the sigils to distinguish things that are variables from anything else that you might type in the program The Perl assignment operator is the equals sign, which takes a variable name on the left side, and gives it the value of the expression on the right.
$length = 8; $length = $length + 4; $length += 4; $str = 'Hello'; $str = $str . " "; $str .= " "; $length **= 3; placing the result back

# same thing with binary assignment operator # append a space to $str # same thing with assignment operator # raise the number in $length to the third power, in $length

When a string literal is double-quoted, it is subject to variable interpolation (besides being checked for backslash escapes). This means that any scalar variable name in the string is replaced with its current value.
$meal = "brontosaurus steak"; $message = "John ate a $meal"; # $message is now "John ate a brontosaurus steak" $message = 'John ate a ' . $meal; # another way to write that

You can get the same results without the double quotes, but the double-quoted string is often the more convenient way to write it.

http://www.learn-with-video-tutorials.com/perl-tutorial-video

The print operator takes a scalar argument and puts it out onto standard output
$message = 'Hello'; print $message;

You can give print a series of values, separated by commas


print "The answer is ", 5 * 3, ".\n"; perl script.pl

Variables have the special "undef" value before they are first assigned. "undef" automatically acts like zero when used as a number and acts like the empty string when used as a string.

Comparison Operators
To compare numbers, Perl has logical comparison operators: <, <=, ==, >=, >, != Each of these returns a true or false value. To compare strings, Perl has an equivalent set of string comparison operators: lt, le, eq, ge, gt, and ne. These compare two strings character-by-character to see whether theyre the same, or whether one comes first in standard string sorting order Comparison Numeric String Equal == eq Not equal != ne Less than < lt Greater than > gt Less than or equal to <= le Greater than or equal to >= ge
45 == 45.0 35 != 30 + 5 '35' eq '35.0' 'fred' lt 'free' 'fred' eq "fred" 'fred' eq 'Fred' # # # # # # true false false (comparing as strings) true true false

The if Control Structure


Like all similar languages, Perl has an if control structure that only executes if its condition returns a true value. If you need an alternative choice, the else keyword provides that as well.
$name = 'John'; if ($name gt 'John') { print "'$name' comes after 'fred' in sorted order.\n"; } else {

http://www.learn-with-video-tutorials.com/perl-tutorial-video

print "'$name' does not come after 'fred'.\n"; print "Maybe it's the same string, in fact.\n"; }

You may use any scalar value as the conditional of the if control structure. Thats handy if you want to store a true or false value into a variable
$is_bigger = $name gt 'John'; if ($is_bigger) { ... }

If the value is a number, 0 means false; all other numbers mean true. If the value is a string, the empty string ('') means false; all other strings mean true. If you need to get the opposite of any Boolean value, use the unary not operator, !.
if (! $is_bigger) { # Do something when $is_bigger is not true }

Getting User Input


To get a value from the keyboard into a Perl program, use the line-input operator, <STDIN> The string value of <STDIN> typically has a newline character on the end of it
$line = <STDIN>; if ($line eq "\n") { print "That was just a blank line!\n"; } else { print "That line of input was: $line"; }

In practice, you dont often want to keep the newline, so you need the chomp() operator. It works on a variable. The variable has to hold a string, and if the string ends in a newline character, chomp() removes the newline
$text = "a line of text\n"; print($text); print("------\n"); chomp($text); print($text); print("------"); # Or the same thing from <STDIN>

As a function, chomp() has a return value, which is the number of characters removed. If a line ends with two or more newlines, chomp() removes only one. If theres no newline, it does nothing, and returns zero Normally, <STDIN> will return a line of text. But if there is no more input, such as at end-of-file, it returns "undef" to signal this. To tell whether a value is undef and not the empty string, use the "defined" function, which returns false for "undef", and true for everything else
$var = <STDIN>;

http://www.learn-with-video-tutorials.com/perl-tutorial-video

if ( defined($var) ) { print "The input was $var"; } else { print "No input available!\n"; }

Loops
A while loop is kind of like a repeated if statement. As long as a condition remains true, an action is repeated over and over. Once the condition is not true, the program moves on
$counter = 0; while ( $counter < 8 ) { print "Counter is less than 8\n"; $counter = $counter + 1; } print "Counter is finally equal to 8"

It's possible to get stuck forever in a while loop. That would happen in the above example if we did not include the statement $x = $x + 1, because $x would remain at the value 0, and the while condition would remain true forever. For loop allows you to specify how many times you want something done, or which items you'd like something done on.
$counter = 0; for ($counter = 0; $counter < 8; $counter++) { print "Counter is less than 8\n"; } print "Counter is finally equal to 8"

We can use simplier "for loop" syntax


for ( 1 .. 5 ) { print "I'm doing this 5 times!\n"; }

Do you want to watch more Perl video lessons? Visit http://www.learn-with-videotutorials.com/perl-tutorial-video

http://www.learn-with-video-tutorials.com/perl-tutorial-video

You might also like