Pages

Hello Perl

As default, usually there's no Perl on Windows. But it is easy to get it, install it, and use it. I have just put Strawberry Perl on my Windows 7 machine and I'm fooling a bit around with it.

In this post I'm going to write a short Perl script, checking if I remember how to do it.

They are just a few lines, just to have an idea of a few features available. What this script does is getting a user input, expected to be a list of at least two comma separated values, and outputting the first and the last one of them. It reads from standard input in an infinite loop, that the user could terminate closing the stream (control-Z on Windows) or sending an interrupt to the program:

#!/usr/bin/perl # 1.
use strict; # 2.
use warnings; # 3.

print "Input a CSV line: ";
while(<>) { # 4.
my @fields = split /,/; # 5.
if(@fields > 1) { # 6.
print "First is $fields[0], last is $fields[$#fields]\n"; # 7.
}
else {
print "Please, insert at least two comma separated values\n";
}

print "New input or interrupt: ";
}

1. This first line is not actually required on Windows, let's think to it as a comment saying that this is a perl script.
2. We ask to the perl interpreter to perform more checks than usual, to help us avoiding silly mistakes.
3. Even more perl checking added.
4. In the angular brakets we access a file as input stream and return a string from it. Here we don't specify which file, so perl assumes we are interested in standard input; and we don't specify where to put the result, so perl puts it in the default ("$_").
5. We declare ("my") an array ("@") and we initialize it with the result of a function ("split") that gets in input a string (not specified, so the default one "$_") and the pattern we want to apply to the string for splitting it.
6. Using an array name in a scalar context gives us the array size.
7. The "$#" notation applied to an array name gives back the index of its last element.

As you can see perl helps us to write code that is very compact but, if you are not in the loop, it is a bit hard to be understood, too.

No comments:

Post a Comment