Try Perl !
Initial
Welcome to Try Perl !
The window on your right is an interactive Perl interpreter.
You can type Perl statements and watch it run.
For your first try, type something like: 3 + 5
LAZY PEOPLE : The code tags like "code tag"
are clikable, so you haven't to type every code snippets, risking a freaky typo... Just click on code tags to test it in the interpreter !
Rules
You could move to next lesson with a next
and go back with back
You could restart to this page with restart
When you're ready, please type next
Reverse the onion
Discover
So you're new to Perl ?
Honestly I envy you, discovering Perl was a big revelation in my IT engineer life...
Perl is built upon some important
principles, here are some :
- There's more than one way to do it. Best way is yours
- When we program, we generally play with strings and... Perl is primarly designed to play with strings. That's so coool!
- As far as possible, stay close to natural language (see Perl poetry)
- Perl is a glue language, allowing to launch shell commands is as easy than accessing SYSV IPC or low level sockets functions.
Start to manipulate things (onions ?! or chunky bacon :P)
Ok start right now without too much blah blah !
Your first exercice is simply to type
reverse "onion"
to reverse the string "onion". Remember that with Perl
easy things are easy to do.
Uppercase
Simple things stay easy with Perl
Perl won't force you to manipulate ASCII values. Perl is convenient because it already provides builtins to handle it for you.
And it's easy, and builtins do what they sound like to do.
Please make me happy by typing uc "onion"
or lc "OnIoN"
...
...Or eventually another string if you really does not like onions,
for instance uc "banana"
is ok for me).
Length
String length
You could retrieve the length of a string like this length "banana"
(yes we now replaced onion per banana after eating onion for several lessons).
As always, we could apply length operator on number because perl will implicitely convert number to a string : length 123
For completeness, please try something else before to continue length 123.00
(length requests a string so 123.00 is converted to 123 !)
Basic Math
Some maths
Remember easy things stay easy to do.
Obviously basic maths functions are availble in Perl.
So you will find builtins like sin, cos, etc... (etc is not one of these ! :P)
Please type cos 2
This is soooo easyyyyyy !
Magic string
The magic x
Please welcome the magic x operator !
This operator is great, to be convinced, type "-" x 40
Take care that x (magic operator) is not * (multiply star).
Try 42 x 10
vs 42 * 10
!
I can't resist to play more with this operator :)
Type "/\\_" x 20
One variable
Hello sigil
One thing that you have to know about Perl is that variables are prefixed by special a character.
You should see it as a good thing, because it allows variable interpolation into strings and helps programmer to know with what kind of data he's dealing with...
The most common/simple variable is the scalar value and it's prefixed by a strikedtrhough S.
Perl users call it sigil but normal people call it dollar (who say truth?).
Here is the famous symbol : $
As we don't even talked about what could contain a scalar variable, let's declare an undefined variable !
Declare your first variable like this : $u = undef
Weakly typed variables
Numbers
A scalar variable could contain a number whatever the precision it is.
Note that I'm talking about number and not integer or floating or whatever.
Until you explicitely need precision (and in this case you need to explicitely set the precision or probably use a Math library...), Perl will simplify your task by taking care of these little things for you.
Declare a number
Declare a number like this : $i = 42
itoa
Implicit conversion to string
Check the content of $i like this : $i
.
Now use implicit conversion like this print $i
(print force string context)
Or use "$i"
in this case this is the quotes that are forcing string context.
Another method is to use concatenation so it force string context like this $i . "min"
Small strings
Your first perl string variable
A scalar variable could contain a string.
Honestly your variables will contain very often strings, because programmers deals a lot with strings.
To prepare next lesson, please put digits between quotes (here : 13), it will still be a string anyway as they are between quotes !
Declare a string like this : $str = " 13 "
And atoi !
Explicit conversion to number
Check the content of $str like this : $str
Now use explicit conversion like this $str + 0.1
or " 40 " + 2.0
Note that it will work with a print like print " 38" + 4
In this case you explicitely reconvert to string after addition.
Note that it is the operator that force conversion, so "41" + "1"
will produce a number with the result that we expect !
Tips
You could use this trick to convert to number by adding 0...
Or you could use sprintf !
Chomp chomp chomp
This is so smart
Everyday, every hours, every minutes... I'm
chomping !
This command provides you an EASY and SAFE way to remove extra trailing characters (generally carriage returns...). It means that you can use with eyes closed !
You must especially use it on data coming from :
- User input
- From curl/ssh/whatever stdout capture from shell command execution
- Or... coming from Mars since we discovered water on it...
Practical work
It's time to play with chomp, but before that, we need a variable... Please start with a variable declaration with one extra space at the end like this
$tor = "onion\n"
.
Ready, steady, Chomp !
Check our dirty Tor
Then we have to check what our $tor variable contains...
To do so, use print "[$tor]"
or "[$tor]"
Finally chomp !
Ok our variable is ready with an extra carriage return at the end...
Now we need to remove this trailing character, let's execute chomp $tor
.
Chomp over there
Conclusion about chomp
We will close these samples around chomp by checking the final content of our $tor variable.
Please check that tariling carriage return was removed with print "($tor)"
.
Chop
There's a bazooka version of chomp that is called chop.
chop does not care about the character but chop in any case !
For instance, if you start chop $tor
it will crop the last "n" from "onion" in the variable $tor !
(Note that it would have worked with a space)
Arrays !
About arrays
Yet you know that Perl variables names have a special character as a prefix...
Arrays are respecting the rules and the symbol is ???
I let you guess...
Please make an effort...
One clue, think that for Scalar it was a S, so for Array it should be ... A !
It's not exactly A actually but @ but that's easy to remember !
Declare a new array
Start with an empty array @empty = ()
Then I let you create a second (non empty) array called @arr like this @arr = ("onion","c","b","a")
Still arrays
Count items
While we have this array initialized, we could try a @arr
and you will probably be a bit surprised by the result.
If you want to inspect @arr content you have to say to perl that you want print @arr
Another method to count the items is to convert the array to a scalar value scalar @arr
Finally I can't resist to show you one more method to know the length of the array...
Type $#arr
to go to the next lesson !
Onion removal
Shift
Before anything else, first have a look at our array with
print @arr
I can't talk about arrays without immediately introduce
shift keyword because you will simply see it almost everywhere in several Perl programs !
Actually, this keyword does 2 things :
- Return the first item of the array
- Remove the item from the array
Ok so let's start practical things. We prepared a
@arr array with a dumb "onion" at the beginning...
I don't want to see "onion" mixed with "c" "b" "a" so we will simply remove it with this command
shift @arr
Unshift
shift has it counterpart
unshift that put an item in an array !
Bubble pop
Pop an item
Perl obviously provides all necessary tools to push and pop items in an array !
In this lesson we will discover pop.
First check what we now have inside our array with print @arr
Alriiight, now we can pop the last item pop @arr
Push a button
Push one
Now that we removed an item (check with
print @arr
if you want), we will just put it again in the array !
Before to do that, I would remind you that :
- push put data at the end of the array !
- Array garanties that insertion order is kept.
Now you can type
push @arr, "a"
Push Push !
Push several
If you want, quicly check array content with print @arr
to see that it well contains "c" "b" "a" !
There's even more to say about push...
You're not limited to scalar values, you can push an array into another array !
As a first excercice, please type push @arr, ()
... But this is not really useful as it just adds nothing to our array :D
The good example is this one push @arr, ( "x", "y", "z" )
For foreach
Foreach
What do we do with arrays ? We
iterate over items !
Let's time to introduce the foreach construction !
Perl foreach is extremly flexible and easy to use...
Try this command :
foreach $v (@arr) { print $v }
Foreach with for
The keyword
foreach could be replaced by
for without any problem.
for $v (@arr) { print $v }
We could also sort/reverse/whatever before iteration like this :
- Reverse :
for $v (reverse @arr) { print $v }
- Sort :
for $v (sort @arr) { print $v }
Splice and range
Range operator
We will play with array portions but first check the content of our extended array with print @arr
Then use range to get only 3 first items print @arr[0..2]
Pizza s(p)lice
Then we could start cutting the cake/onion/rope/whatever !
Go with this command @arr = splice @arr, 0, 3
(Note that 3 is the length where the 2 above in range was the index !)
Getting items
Accessing item
To access an item in the array, you could do a $arr[1]
.
Oh my God, why the prefixed symbol moved from @ to $ ??
Don't panic, keep calm and take a beer...
The symbol used depend from what you want to access, here we want a scalar value, so we use $ !
Accessing multiple values
To get multiple values at once, there's a magic assignment in Perl, that produce jealousy from all other programming languages : Parallel multi assignment !
Please try ($a, $b, $c) = @arr
The left value of the assignment requests 3 variables, so Perl get 3 first items from @arr. And it handles correctly if there are few items and ignore extra items !Thank you Perl !
Playing with items
Checking our extracted items
Now check that
$a,
$b and
$c contains the right data :
The good news is
$b produce "b" but we have some trouble with
$a and
$c... We need to switch them !
Exchange values
I ask you to keep your eyes wide open because it's really beautiful !
Type
($c, $a) = ($a, $c)
or
($a, $c) = ($c, $a)
No more mess
Print exchanged values
Now we can print our data with switched values :
- With a classic
print "$a$b$c"
- Or using commas like this
print $a, $b, $c
- Or with formatted printf like
printf("%s%s%s", $a, $b, $c)
Note that printf will be more useful for formatting.
That's all for this lesson !
Sorting
Check dirty array
While we played with $a, $b and $c, we forget about our initial @arr...
Let's check our @arr with print @arr
to see that items are still in dumb order "c", "b", "a" !
Sort items
Then we could sort the array with print( sort @arr )
Soooo easyyyy right ?!
Endless
Last item
If we want the last item, whatever the index, we have several manner to do so :
- We could do a
$arr[$#arr]
- Or we could do a
$arr[-1]
- Or even we could do a
$arr[@arr-1]
Yeah baby, there's more than one way to do it, remember !
String concatenation
Join
We still have our @arr filled with dummy "c", "b", "a"...
But now I want to print array items separated by commas. But I don't want to handle parity (no commas at the end without item).
Simply type join(",",@arr)
or join ",",@arr
As I'm a joker, I propose that you could do something even weird like join(" <--> ",@arr)
or join " <--> ",@arr
Perl is also known as practical extraction and report language, formatting data is extremly easy !
Sky only is the limit !
Banana split
From raw to structured data
Manipulating string with Perl is extremly easy, I repeat !
Let's discover the split keyword :
split let you feed structured data from raw strings without too much effort !
The most typical example is join("-", split(",", "john,doe,30"))
(Please note that we put a join to pretty print the result in this terminal)
You can use whatever separator even multi characters separator :
join("-", split("::", "john::doe::30"))
Handling empty fields without any effort :
join("-", split(",", "john,,doe,30,,,"))
Then finally please retrieve split data in separate variables like this :
($f, $l, $a) = split(",", "john,doe,30")
Split result
Checking your split
Let's check the result of our split with print "$f $l $a"
This is soooo easyyyyyy !
Conditions
if-then-else !
We are not going to do too much things if we are not able to execute code upon conditions...
No surprise, Perl provides the famous
if then else :
if (1) { print "onion" }
Some things to remember :
- You have to put braces (if(1) print "stuff" is simply invalid)
- The keyword to combine else and if is elsif
Do if unless
Just do it !
Perl true and false is intuitive...
Consider only what is false and deduce that everything else is true
Note that not or ! (exclamation mark) are returning the logical negation.
To test true and false values, please welcome do if construction !
First type do { print "onion" } if 1
The exact contrary is unless: do { print "onion" } unless 0
Same construction apply without the do, for instance you could try not with print "onion" if not 0
True lies
Who to trust ?
So now what is
false :
- 0 is false
- "0" is false
- 0.0 is false
- undef is false
- Empty array () is false
To summarize you can type (and note somewhere maybe) something like :
!(0 or "0" or 0.0 or undef or ()) and print "false"
So what is
true ?
- " " is true
- "0.0" is true
- 1 is true
- "banana" is true
To summarize you can type something like :
" " and "0.0" and 1 and "banana" and print "true"
It's logic !
Logical expressions
In Perl, we like to do
one liner logical execution.
If you don't understand what I'm talking about it's like when you do with bash
./configure && make && sudo make install.
It means that you will execute
make depending the result of
./configure script.
With perl we use and abuse of these logical expressions and we even have more operators for it than any other language !
Please make me happy and test some of these statements :
1 and print "onion"
1 && print "onion"
0 or print "onion"
0 || print "onion"
Cool right ?
0 and print "banana" or print "onion"
Ternary operator
Short if-then-else !
Let's introduce ternary operator !
Maybe you know it from another language (C for instance)...
So I let you try these examples :
- Execute then :
0 ? print "true" : print "false"
- Execute else :
1 ? print "true" : print "false"
Hash
Powerful tr(h)ash
There's a variable type that we do not mentionned yet... The famous hash !
As other Perl variables, an hash is prefixed by a special symbol...
I could let you guess what is the prefix but this time, it's not something really close to a H... as it's % !
So first define an empty hash %empty = ()
Then we will do something more useul %h = ( key1 => "val1", key2 => "val2" )
Still hashes
Looking inside hash
To retrieve the value that you stored in the box named
"key2" in your hash
%h...
You should use one of these methods :
- Classic :
$h{"key2"}
- Ventilated with spaces :
$h { "key2" }
- Simple quote :
$h{'key2'}
- Even without quotes :
$h{key2}
Note that we use a
$ as we want to access a scalar value !
We could also print the whole hash with
print %h
This is really basic and ugly way to print the hash, no need to say that there are a lot of other ways to pretty print an hash !
Next lesson will describe some other methods, but the goal is not to pretty print the hash but to discover how to play with hashes :)
Hashes of onions
Keys and values
Note that join also works on hashes so print join "-",%h
will produce what we want.
What if we only want keys ?
To do so, use a print keys %h
Same for values ?
print values %h
!
NOTA BENE : an hash does not preserve any (insertion) order but put data in a special way (internally) to access it quickly. It means that you often have to do your own sorting !
Variable types
Scalar , arrays and hash !
Now that we have introduced variables, we will dig a bit more into it.
First we could inspect a variable type :
Note that we forget about the fourth type which is the function type, but please ignore it at the moment.
What we have is a
first level reference it means that we get the key of the variable in the Perl internals, and we know that this key is pointing to a scalar, array or hash.
Then try something like
\\$s
and see what we got for a
second level reference
Refs
Referencing
I will introduce references, but honestly I will do it quickly as references are not intented for beginners.
For lucky C programmers, references are like pointers in C but with a key difference that it's not real memory location but some place relative to perl variable table.
It means that instead of playing with scalar, array or hash you will have a kind of key that is referencing to your data.
The operator to reference a variable is \ (backslash).
There's no limitation in the number of reference levels for a variable...
...But the good sense should prevent you to do some dummy \\\\\\%h
Derefs
Dereferencing
To dereference, you have to cast (sort of) to the type that you want.
For our tests we will reuse our @arr and %h
Take reference of our array then dereference to an array and print it :
print @{ \@arr }
Take reference of our hash then dereference to an hash and print it :
print %{ \%h }
Note that we use the prefix symbol of the variable type (@ and %).
And while we are discussing about dereferencing types, trying to dereference an array as a hash and vice versa will just produce an error !
Subs
Functions
In Perl, functions are called sub as sub procedure !
Perl sub declaration are extremly flexible :
No need to explicitely give return type : sub f1() { print "f1" } f1()
No need to exploicitely give parameters : sub f2 { print "f2" } f2("a")
If parameters are given, possible optional parameters after a semi colon : sub f3($;$$) { print "f3" } f3("a","b")
So Perl functions declaration are exremly flexible !
Function type
I won't discuss too much about it but a sub is also a variable type and could be threated as is and dereferenced for instance ...
Please try \&s
and finally &{ sub { print "f4" }}()
Grep
Introduction to regex
Perl is well known to be the best language to use with regular expression.
Perl even produced standard PCRE which stands for Perl Compatible Regular Expression !
First we will start with a grep :
Please type grep {/onion/} "onion and bacon" and print "get it"
There's also another way to test a string, please try :
if ("onion" =~ /nio/) { print "match"}
World map
Introduction to map
Perl provides a command to apply an action to a list of data. It's called map !
Please give it a try with print map {ucfirst $_} ("aa", "bb", "cc")
Oh, wait, I need to explain what is $_ ?!
It's only the current item !
Perl culture
Yet Another Perl Hacker
If you are here, that's because you're interested in Perl and ready to learn more about it...
So before concluding I need to talk about Perl culture...
Perl community is
huge and
valuable :
Perl programmers are funny (look at
Acme modules in
CPAN).
Perl programmers often play with obfuscated code.
To conclude please type (or click lazy people) on this snippet :
$_ = "Jvtu bopuifs Pfsm ibdlfs"; y/a-z/za-y/; print
Extra bonus tips
Think about using
use strict and
use warnings !!!
Onion award
To go further
You successfully finished the tutorial about Perl.
I hope you enjoyed the tutorial and learned a lot of stuff. I really made it with love !
I recommend that you start right now to test things on your computer...
...Or visit websites to learn more about Perl.
What could I recommend as further readings ?
- Programming Perl also called The Camel Book
- Modern Perl Programming
Get your medal
As an award, please get this onion picture as a gift !