„Freiheit oder Tod“
 
This article is for people already familiar with another programming or scripting language. This document can give one a short introduction to perl, the practical programming/scripting language.


The very basics



Example 1: assigning values to a variable

1: #!/usr/bin/env perl
2: use strict;
3: 
4: my $variable = "some content\n";
5: print $variable;


Example 2: finding strings

01: #!/usr/bin/env perl
02: use strict;
03: 
04: my $crazyString = "if a horse get's hot, it's probably eaten by me";
05: 
06: # a horse has been found
07: if (index($crazyString, "horse")!=-1) {
08:         print "a horse has been found\n";
09: }
10: 
11: # a dog has _not_ been found
12: if (index($crazyString, "dog")==-1) {
13:         print "a dog has _not_ been found\n";
14: }


Example 3: splitting a string into an array

01: #!/usr/bin/env perl
02: use strict;
03: 
04: my $crazyString = "if a horse get's hot, it's probably eaten by me";
05: 
06: # you can split strings with "split"
07: # this will give you an array with the splitted results
08: my @sentenceSplit = split(/,/, $crazyString);
09: print "first part: ".$sentenceSplit[0]."\n";
10: print "second part: ".$sentenceSplit[1]."\n";


Example 4: upper and lowercase

1: #!/usr/bin/env perl
2: use strict;
3: 
4: my $mixedcaseString = "HALlo";
5: print lc($mixedcaseString)."\n";
6: print uc($mixedcaseString)."\n";


Example 5: replacing strings

01: #!/usr/bin/env perl
02: use strict;
03: 
04: my $string = "Hello, my name is Bill Gates and Bill Gates is cool!\n";
05: # only replaces the first occurance
06: $string =~ s/Bill Gates/Andreas Schipplock/;
07: print $string; 
08:
09: my $nString = "Hello, my name is Bill Gates and Bill Gates is cool!\n"; 10: # replaces all occurences 11: $nString =~ s/Bill Gates/Andreas Schipplock/g; 12: print $nString;


Example 6: simple arrays

01: #!/usr/bin/env perl
02: use strict;
03: 
04: my @array = ("item 1", "item 2", "item 3", "item 4");
05: 
06: # print a single item
07: print $array[1]."\n"; # item 2
08: 
09: # push into the array
10: push @array, "freaky stuff";
11: 
12: # go through the whole array
13: for (my $run=0;$run<(@array);$run++) {
14:         print "entry ".$run.": ".$array[$run]."\n";
15: }


Example 7: simple array of hashes

01: #!/usr/bin/env perl
02: use strict;
03: 
04: my @array = ({"name", "tim tailor"}, {"name", "al borland"});
05: 
06: print $array[0]{"name"}."\n";
07: 
08: for (my $run=0;$run<(@array);$run++) {
09:         print "entry ".$run.": ".$array[$run]{"name"}."\n";
10: }


Example 8: advanced array of hashes

01: #!/usr/bin/env perl
02: use strict;
03: 
04: my @arrayOfHashes = ({
05:         "name" =>"tim tailor",
06:         "country" => "usa"
07: },
08: {
09:         "name" => "al borland",
10:         "country" => "germany"
11: });
12: 
13: for (my $run=0;$run<(@arrayOfHashes);$run++) {
14:     print "entry ".$run.": ".$arrayOfHashes[$run]{"name"}.", ";
15:     print "country: ".$arrayOfHashes[$run]{"country"}."\n";
16: }


Example 9: pushing a hash into an existing array of hashes

01: #!/usr/bin/env perl
02: use strict;
03: 
04: my @arrayOfHashes = ({
05:                                 "name" =>"tim tailor",
06:                                 "country" => "usa"
07:                          },
08:                          {
09:                                 "name" => "al borland",
10:                                 "country" => "germany"
11:                          });
12: 
13: for (my $run=0;$run<(@arrayOfHashes);$run++) {
14:         print "entry ".$run.": ".$arrayOfHashes[$run]{"name"}.", ";
15:         print "country: ".$arrayOfHashes[$run]{"country"}."\n";
16: }
17: 
18: # pushing a hash into an array with existing hashes
19: push @arrayOfHashes, {"name"=>"andreas schipplock","country"=>"germany"};
20: 
21: for (my $run=0;$run<(@arrayOfHashes);$run++) {
22:         print "entry ".$run.": ".$arrayOfHashes[$run]{"name"}.", ";
23:         print "country: ".$arrayOfHashes[$run]{"country"}."\n";
24: }




File operations


Opening a file and printing its content


printfile.pl
01: #!/usr/bin/env perl
02: use strict;
03: 
04: open THEFILE, "</proc/cpuinfo" or die("error opening file");
05: 
06: my @lines = <THEFILE>; # each line is an entry in the array
07: 
08: # now some "fun"
09: for (my $run=0;$run<(@lines);$run++) {
10:         if (index($lines[$run], ":")!=-1) {
11:                 my @infoSplit = split(/:/, $lines[$run]);
12:                 # remove unneeded crap
13:                 $infoSplit[0] =~ s/^\s+|\s+$//g; # removes ws and linebreak
14:                 $infoSplit[1] =~ s/^\s+|\s+$//g; # " "
15:                 $infoSplit[0] =~ s/\t//g; # removes all tabs
16:                 $infoSplit[1] =~ s/\t//g; # " "
17:                 # print the cpuinfo: $key:$value\n
18:                 print $infoSplit[0].":".$infoSplit[1]."\n";
19:         }
20: }
21: 
22: close THEFILE;


Opening a file and saving its content to a new one


savefile.pl
01: #!/usr/bin/env perl
02: use strict;
03: 
04: # open the file /proc/cpuinfo in readonly mode
05: open THEFILE, "</proc/cpuinfo" or die("error opening file");
06: 
07: # the contents of /tmp/cpuinfo will be overriden here
08: # to append content to a file use >> instead of > here
09: open THENEWFILE, ">/tmp/cpuinfo" or die("error creating the file");
10: 
11: my @lines = <THEFILE>; # each line is an entry in the array
12: 
13: # parses the cpuinfo file, modifies it, saves it to a new file
14: for (my $run=0;$run<(@lines);$run++) {
15:         if (index($lines[$run], ":")!=-1) {
16:                 my @infoSplit = split(/:/, $lines[$run]);
17:                 # remove unneeded crap
18:                 $infoSplit[0] =~ s/^\s+|\s+$//g; # removes ws and linebreak
19:                 $infoSplit[1] =~ s/^\s+|\s+$//g; # " "
20:                 $infoSplit[0] =~ s/\t//g; # removes all tabs
21:                 $infoSplit[1] =~ s/\t//g; # " "
22:                 # print the modified content into the new file
23:                 print THENEWFILE $infoSplit[0]."=>".$infoSplit[1]."\n";
24:         }
25: }
26: 
27: close THENEWFILE;
28: close THEFILE;




Object Orientation


a simple package (aka class, module etc...)


database.pm
01: #!/usr/bin/perl
02: use strict;
03: 
04: package Database; 05:
06: sub new { 07: my $self = {}; 08:
09: $self->{_hostname} = $_[0]; 10: $self->{_username} = $_[1]; 11: $self->{_password} = $_[2]; 12:
13: bless $self, shift; 14: $self->init($self->{_hostname}, $self->{_username}, $self->{_password}); 15: return $self; 16: } 17:
18: sub init { 19: my ($self, $hostname, $username, $password) = @_; 20: $self->setHostname($hostname); 21: $self->setUsername($username); 22: $self->setPassword($password); 23: } 24:
25: sub setHostname { 26: my ($self, $hostname) = @_; 27: $self->{_hostname} = $hostname; 28: } 29:
30: sub getHostname { 31: my ($self) = @_; 32: return $self->{_hostname}; 33: } 34:
35: sub setUsername { 36: my ($self, $username) = @_; 37: $self->{_username} = $username; 38: } 39:
40: sub getUsername { 41: my ($self) = @_; 42: return $self->{_username}; 43: } 44:
45: sub setPassword { 46: my ($self, $password) = @_; 47: $self->{_password} = $password; 48: } 49:
50: sub getPassword { 51: my ($self) = @_; 52: return $self->{_password}; 53: } 54:
55: 1;


test.pl
1: #!/usr/bin/env perl
2: use strict;
3: use database;
4: 
5: my $database = new Database("localhost", "root", "superpassword"); 6:
7: print $database->getUsername()."\n";