Perl Hello Script

Perl Logo

This is the next installment of the Hello Script series – Hello Script for Perl. ‘Hello Script’ is a file that contains the most commonly used elements of a programming language so that it can be used as a cheat sheet when working with that language.

Introduction to Perl

For those of who are unfamiliar with perl, here is the Wikipedia definition…

Perl is a dynamic programming language created by Larry Wall and first released in 1987. Perl borrows features from a variety of other languages including C, shell scripting (sh), AWK, sed and Lisp. Perl was widely adopted for its strengths in text processing and lack of the arbitrary limitations of many scripting languages at the time.

If you are interested in learning perl, I have written a Perl Tutorial. And here are some more links if you are interested

Hello Script for Perl


#!/usr/bin/perl
use strict;
use warnings;

# Printing(IO)
print "Hello World!\n";

# Variables, concatenation
my $name = 'Binny';
my $year = 2008;
print "Hello, " . $name . " - welcome to " . $year . "\n";

#If,else conditions
if ($year > 2008) {
	print "Welcome to the future - yes, we have flying cars!";
}
elsif($year < 2008) {
	print "The past - please don't change anything. Don't step on any butterflies. And for the sake of all that's good and holy, stay away from your parents!";
}
else {
	print "Anything wrong with your time machine? You have not gone anywhere, kiddo.";
}
print "\n";

# For loop
for(my $i=0; $i<3; $i++) {
	print "$i) Hi there!\n";
}

#Numerical Array, foreach
my @rules = (
	'Do no harm',
	'Obey',
	'Continue Living'
);
my $i = 1;
foreach my $rule (@rules) {
	print "Rule " . $i . " : " . $rule . "\n";
	$i++;
}

# Associated array, while
my %associated = (
	'hello'	=>	'world',
	'foo'	=>	'bar',
	'lorem'	=>	'ipsum'
);
while(my ($key, $value) = each(%associated)) {
	print "$key: $value\n";
}

# Using Join and Split
my @csv_values = split(',', "hello,world,how,are,you\n");
print join(":", @csv_values);

# Function, argument, return, call
sub hello {
	$name = shift; #First argument.
	return "Hello " . $name;
}
print hello("Binny");

# File IO
# File reading, easy method...
open(IN,'Hello.pl') or die("Cannot open file : $!");
my @lines = <IN>;
close(IN);
my $contents = join('',@lines);
print "Hello has " . length($contents) . " chars\n";
# Writing to a file
open(OUT, '>/tmp/hello.txt');
print OUT "Hello World";
close(OUT);
 
# Command Executing
print `ls`; #Execute the command 'ls' and print its output
print "\n";
 
# Regular Expressions
my $string = "Hello World";
print "Yup - its evil\n" if($string =~ /^Hell/);
$string =~ s/l([^l])/$1/g; #Remove an 'l' from both words. Should print 'Helo Word'
print $string;


print "\n\n";
About Binny V A 102 Articles
Freelance Web Developer on the LAMP Platform. Maintains a blogs http://blog.binnyva.com/. Other sites include Bin-Co and OpenJS

1 Comment

Leave a Reply

Your email address will not be published.


*