Duke is a Java developer with 5 years of experience. One day, Duke got curious and wanted to learn something about a language called Perl. Duke has a friend, Larry. Larry is a Perl developer for quite some time now. He’s an experienced developer, he know multiple languages, including Java. He played around with it in his college days.
Duke has a sit down with his friend Larry to begin his initiation in the land of Perl. They start from the basics. Larry tells Duke all about the basic Perl 5 data types, Perl 5 special variables and building web apps in Perl.
Perl has three basic data types: scalar, array and hash.
Scalar
Imagine a world without primitives, a world where each variable adapts to the context it is being used.
Every junior Java developer knows that we test boolean equality with false/true.
Boolean name=false; if boolean==true then do something
In old fashion Perl we use the value 0 for negative/false. This means that 0 will behave like false when it is used in an if clause and numeric when you add a number to it. Perl scalar type contains all the Java primitive types. Scalar in Perl is defined with a $ sign and then the name of the variable.
Perl: $variable=12; $variable=”string”
Array
Imagine a world where it doesn’t matter what kind of data you have, they can all be part of the same array. In Perl we have data type @array. An array is just like any other array from other languages, but in Perl you don’t have to define the element type.
Perl:@array=(1,”string”,2.3497585…)
This is a very close example of an ArrayList<Object> in Java.
Java: ArrayList<Object>array=new ArrayList<Object>();
You can put any kind of data into array because in Java every object is a subclass of Object.
Hash
A hash is like a dictionary. You have a word and a meaning attached to it. A Perl has is a collection of key-value pairs. Each key must be unique. An example of this would be:
Perl: %hash=(key=>value, key1=>value1, …)
The closest Java data structure could be the HashMap<String, Object>
Each element from a HashMap can be identified from a unique ID and it can be of any type.
Java: HashMap<String, Object> hashMap=new HashMap<String, Object>();
hashMap.put(“numeric”, new Integer(1)); hashMap.put”string”, “2”).
Each variable has an address. References in Perl are defined with \ in front.
Example: my $arrayref= \@array; my $hashref= \%hash.
Privacy
We have three levels of privacy for a variable: my, our, local. Our variable is visible in multiple packages and my is visible only in the current package. A local variable allows us to redefine a variable which was used before.
Function calls
In C and in Java each function has a signature. When defining a function you must specify the number and the type of each parameter received. In Perl you mustn’t do that. You can call the same Perl function with one, two or one hundred parameters. It will work.
Java:void String substring(int a , int b){…}
Perl: sub substring{
my ($a, $b)=@_;
}
You probably noticed the strange @_ sign. @_ contains the parameters sent by the caller. This is a special Perl variable. See more here.
Loops
Perl implements all the traditional loops, it has also a foreach loop.
Java: for(String item : items){
System.out.println(item);
}
Perl: foreach my $item(@items){
print $item;
}
Perl and OOP
There is an old way and a modern way to do Perl OOP. The good old way is to create the module and in the constructor create a hash and then bless it.
sub new { my $self = bless { };
return $self;
}
This way the Perl package will behave like an object and can call subroutines like methods.
my $perlobject = Perlpackage->new();
Now we can call $perlobject->method. Each time we call a method from an object the first parameter will always be a reference to the object itself.
The new way is to use Moose. Moose is a library that allows you to use in Perl more modern OOP features like strong prototyping, inheritance and roles.
Perl ORM
Perl is a very old language, used in the dawn of the web age. It has modules for communicating the mainstream database servers. It also has very nice ORM which uses Moose. Check DBIx class here.
Perl and CPAN
Perl has a lovely store called CPAN. This is a large warehouse of Perl modules where you can find basically everything that your mind can imagine.
Perl and the Web
As you probably know, early web development was done via CGI scripts. Contemporary solutions in Perl are frameworks like Catalyst, Dancer and Mojolicious.
Imagine these frameworks just like any other Java web development framework (Spring). An important aspect in Perl is the implementation of a REST API.
Here is a nice exercise.
Create a web response with the following json:
{“id”:1,“content”:“Hello, World!”}
Java – taken from spring.io
- Create a POJO for json
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
- Create the controller
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = “Hello, %s!”;
private final AtomicLong counter = new AtomicLong();
@RequestMapping(“/greeting”)
public Greeting greeting(@RequestParam(value=“name”, defaultValue=“World”) String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
- Access http://localhost:8080/greeting and get the response
Perl (Dancer as a framework)
use Dancer2; |
use JSON;
get ‘/greeting’ => sub {
content_type ‘application/json’;
return to_json { id => $counter, content => “Hello World” };
};
dance();
1;
Perl 6
All examples from this article were using Perl 5. A new Perl has recently been released, PERL 6 which has lot’s of fun stuff. Perl 6 is not an upgraded version of Perl 5 , but a new member of the Perl family. More info about the wonderful Perl 6 here.
Mihai Szilagyi