Learning Perl.

May 19, 2011 | Scripting and programming, Technology | 0 comments

I started a Perl class week last Wednesday and last night was my second night attending it. The class is being held in TOG It is an organization / group of people called the Dublin hacker space. I have no idea how TOG equates to Dublin hacker space and I haven’t asked yet so sorry about that.

I’m finding the Perl language and syntax to be very interesting. It’s similar in a lot of ways to Javascript and VBScript but in most ways it’s wildly different. Some things I’m really liking about it and some things are taking a little longer to sink in.

As a demonstration of what I know about Perl at this very early stage, here’s a simple script that contains the months of the years and the number of days in each one. This information is contained in a hash or dictionary. At one stgae the hash is converted into an array. It wasn’t really necessary to do this but I did it for practise anyway. I’m also using an if statement and a while loop in here too just to keep things interesting.

One thing I love about Perl is it’s readability. You’ll notice that in the looop I have if statements after each print statement. This is nice because it reads from left to right very naturally.

at the end of the script I’m also not using quotes for the string, I’m using qq/ instead. This allows me to surround the value of the variable in quotations when I’m printing it to the screen.

It’s all very straight forward at this stage but I’m only really a week into it as the first time I ever wrote a line of Perl was last Wednesday..

#!/usr/bin/env perl -w
my %months = (“January” => 31, “February” => 28, “March” => 31, “April” => 30, “May” => 31, “June” => 30, “July” => 31, “August” => 31, “September” => 30, “October” => 31, “November” => 30,”December” => 31);
my $choice = “”;
my @arrMonths = keys %months;
print “The months you can choose from are: @arrMonths”;
print “What month do you want to show? “;
chomp ($choice = <>);
my $day = 1;
if (exists $months{$choice}) {
print “There are $months{$choice} days in $choice”;
while ($day <= $months{$choice}) { print "$day t" if ($day <= $months{$choice}); $day ++; print "$day t" if ($day <= $months{$choice}); $day ++; print "$day t" if ($day <= $months{$choice}); print "n"; $day ++; next } } else { print qq/The string you attempted to input is not a valid month. "$choice". n / }

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.