Perl

From Partyvan Wiki

Jump to: navigation, search

This article is not intended for those new to programming
For beginner-friendly articles, see PHP and Python


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.

Structurally, Perl is a brainfuck comparable to C.

For moar info, see the Perl article on wikipedia.

Some of the tools the Insurgency uses, such as mt_pulse.pl, use Perl. Linux and BSD distros usually include Perl as a default package. Windows users should get strawberryperl and Macfags should get ActivePerl from the link below.

Perl has a lot of documentation, you should use the perldoc command for "man-like" documentation of functions and other aspects of the perl language.
You should also check perl.org and various other related sites such as perldoc and cpan.
Use perldoc perlfunc in a system where perl is installed for documentation of built-in perl functions (such as qw, print, sort, rand, etc.).

Contents

How to get Perl

Windows

  1. Download the Strawberry Perl installer from here
  2. Run the program and follow the instructions
  3. Open Command prompt and run "perl -v", You should see "The is perl.." This means Perl is installed properly.

Linux

On Ubuntu/Debian you can simply use the "apt-get" command

sudo apt-get install perl

On Redhat/fedora

sudo yum install perl

on suse

sudo yast install perl

on Arch Linux

sudo pacman -S perl

on Gentoo

sudo emerge -av perl

Manual Install

i.  Download Perl 5.8.1 from : 
      http://www.perl.com/CPAN/src/stable.tar.gz
ii. Remove the old Perl from the system before building
      # rm -rf /usr/lib/perl5
p/s : Suggestion from jeremy
      # mv /usr/lib/perl5 /root/perl5backup

Installation :

i.   # tar xvzf stable.tar.gz
ii.  # cd perl-5.8.1
iii. For more information , # ./Configure --help
     # ./Configure -de \
         -Dprefix=/usr \
         -Dcccdlflags='-fPIC' \
         -Darchname=i386-linux 
iv.  # make
v.   # make test
vi.  # make install

Post Installation :

i.   # perl -MCPAN -e shell 
     Just Follow step by step. Use the Default Answer for all (just press enter).
ii.  install Bundle::CPAN
iii. install Bundle::LWP
iv.  install Bundle::DBI
v.   install DBD::mysql

To test the install run.

perl -v

Learning Perl

Though there are several books available to someone wanting to learn perl, O'Reilly's "Learning Perl" is widely considered to be the best book for newcomers to Perl.

Getting Started

Please note that if there are any terms or structures that you do not understand while reading, just keep reading because they are explained later on in the tutorial.

Hello World

A basic hello world example in perl.

#!/usr/bin/perl
#This will print "Hello World!"
print("Hello world!");

The #!/usr/bin/perl tells the operating system where the perl interpreter is located on your computer. This will be ignored on windows, and isn't required for it, but it should be left in for *NIX users.

The # denotes a comment in perl, comments are purely to make it easier for humans to understand what the code is (supposed to be) doing.

Then finally print, of course, prints the text which is in the quotes to the screen.

Variables

There are several different types of variables in perl denoted by different symbols these are scalar ($), arrays (@), hashes (%), subroutines (&), and typeglobals which use (*).

Scalar

Basically, scalars are what you could expect of a "variable" in perl, however, they can be anything, from integers to floats to strings to objects, etc.

#!/usr/bin/perl
 
use strict; #Make sure we use proper coding conventions
 
#Declaring an integer is easy, just use "my" the first time you use it, then use 
#the equals sign to set it to whatever Number you want
my $integer = 1; 
 
#print can take and print multiple arguments separated by a comma. The first argument is our integer to be printed
#The second argument is an escaped newline (which prints a "new line", how novel.) 
#An actual newline shouldn't be used since it would shift your code down a line (obviously)
#the newline character is usually required, if you omit it, the next thing you print will appear alongside what you just printed.
print($integer, "\n");
#you can also use a different syntax for print:
print $integer, "\n"; #it works the exact same way as the other one, it's a matter of style.
 
#Declaring a float (essentially an integer with more precision, a decimal place!) is the same
my $float = 3.9;
 
#you can use comments wherever you want in your code, but make sure not to put
#any comments in front of your code, since you can't partyvan.info close them
#like this# print($float, "\n");
#as comments only end at the end of the line in perl
#you can also put comments at the end of a line
print "penis\n"; #like this
 
#declaring a string is simple. if you don't need to use any escaped characters like \n
#you can just put it in single quotes like so:
my $string = 'loldongs';
#this makes the string "literal", i.e. any variable names or special characters (like \n) are not parsed into their "normal" meanings
 
#otherwise you put it in double quotes, like this:
my $otherString = "lol\ndongs";
#you can also put a variable in a double quoted string to put its value in it, like this:
my $yetAnotherString = "$float $string"; #which is the same as "3.9 loldongs"
 
my $areWeDone = "All Done With Scalars!\n";
 
print($areWeDone); #yes we are

See also: print on Perldoc.

Arrays

Arrays in perl are the easiest data type to work with next to scalars. Arrays can hold pretty much any other data type, including other arrays and hashes.

array1.pl

#!/usr/bin/perl
 
use strict;
 
#You can use qw to define array elements without using quotes
#qw can be enclosed with pretty much any character, but you should probably
#use a relatively uncommon character for it, since any occurrence of that
#character will end / start the array
#for this reason, I use the vertical pipe ( | )
 
my @names = qw|Fred Aaron Julie Tom|;
 
my @sortedNames = sort(@names); #fill the new array with the elements from the old array sorted alphabetically
 
foreach my $name (@sortedNames) { #for every name in the list
	print($name, "\n"); #print it with a newline
}

For more info: see qw on Perldoc and sort on Perldoc.

Now for a complex example:

array2.pl

#!/usr/bin/perl
 
use strict;
 
my @insultNouns = qw|Buffoon Idiot Moron Lamebrain|;
my @insultAdjs = qw|Stinky Stupid Fat Pompous|;
 
#rand() takes one argument, an upper limit for the random number. We use the 
#element index (defined by the $# symbol) as the upper limit, adding 0.5
#so the last element has an equal chance of being selected as any other number
#since rand() returns a float by default, we convert it to an integer
 
my $nounNum = int rand($#insultNouns + 0.5);
my $adjNum =  int rand($#insultAdjs + 0.5);
 
my $insultingName = $insultAdjs[$adjNum]; #Start off the name with an insulting adjective
$insultingName .= " ".$insultNouns[$nounNum]; #Stick a space and a noun onto the end
print($insultingName, "\n"); #print out the result

For more info: see rand on Perldoc.

In perl, there are (literally) over 9000 ways to complete any given task. Here is a further compacted version of the previous example:

array2b.pl

#!/usr/bin/perl
 
use strict;
 
my @insultNouns = qw|Buffoon Idiot Moron Lamebrain|;
my @insultAdjs = qw|Stinky Stupid Fat Pompous|;
 
#You can either choose readability or compactness of code, it's up to you.
#Though if compactness is really of concern to you, consider creating subs to handle common tasks
print($insultAdjs[int rand($#insultAdjs + 0.5)], " ", $insultNouns[int rand($#insultNouns + 0.5)],"\n");

You can do a lot of interesting things with arrays. In this example, two arrays are used to populate a hash filled with login details:

array3.pl

#!/usr/bin/perl
 
use strict;
 
my %userInfo; #declare an empty hash (associative array)
my @userNames = ('billjohnston', 'johndoe', 'janedoe', 'alroker'); #this is the best way to define array contents
                                                                   #only use qw if you're feeling lazy.
my @userPasswords = ('Baseball1', 'ungnome', 'GrApEs634', 'Sl1mNTr1m');
 
for (0..$#userNames){ #if there are 4 elements in @usernames, this will loop 5 times
# $_ is a special variable that will be explained later
	$userInfo{$userNames[$_]} = $userPasswords[$_]; #convert the two arrays to a hash
}
 
print('Username: '); 
chomp(my $username = <STDIN>); #take input from the user, ignoring ending newline
                               #chomp basically removes the trailing \r\n (or just \n)
                               #which you usually get when reading input or from a file.
print('Password: '); 
chomp(my $password = <STDIN>);
print("\n");
 
if ($userInfo{$username} eq $password){
	print($username, '@localhost#~ '); #using a comma in a print is prefered to using the . concatenation operator
	                                   #using a . forces perl to treat the scalar as a string
	chomp(my $command = <STDIN>); #just wait for the user to press enter;
	print("Error, Exiting\n");
}else{
	print("Incorrect Username or Password.\n");
}

For more info: see chomp on Perldoc.

Hashes

In Perl, a hash is an associative array; in other words, rather than using numbers as an index, it uses strings, which are called keys. They're comparable to maps in PHP and dictionaries in Python (except unordered).

hash1.pl

#!/usr/bin/perl
 
use strict;
 
#hashes are signified by the % symbol
#The proper way to initialize a hash is ('Key' => 'Value');
#you then access the a value in the hash using the
#$hashName{$key} syntax
#you can use a variable as the element name or just use a plain string
my %userConfig = (	'Name' => 'Anonymous',
			'Prompt' => 'I did it for the ____',
			'Password' => 'lulz',
			'Secret' => 'The Game' );
#as a sidenote, if you define an nonexistent hash key, it creates that key
#for example, "$userConfig{'Date'} = 'Yesterday';" would create a key named 'Date' in hash %userConfig
 
print("Welcome, ", $userConfig{'Name'}, "\n"); #prints "Welcome, Anonymous"
print($userConfig{'Prompt'}, ": "); #prints "I did it for the ____"
chomp(my $password = <STDIN>);
#reads from STDIN (user input), stores into the variable $password and then chomp()s its newline.
 
if($password eq $userConfig{'Password'}){ #if the password the user input is the same as the one defined in %userConfig
	print("\nSecret: ",$userConfig{'Secret'}, "\n"); #prints "Secret: The Game"
}else{ #otherwise, the password did not match
	print("\nGet out, spai.\n");
}

hash2.pl

#!/usr/bin/perl
 
use strict;
 
my @users = (
	{'Name' => 'James', 'Age' => 21},
	{'Name' => 'Adam', 'Age' => 37},
	{'Name' => 'Paul', 'Age' => 19}
); #define an array with 3 hashes inside
   #if you want to keep your hashes ordered, you have to put them inside an array
   #or (do it another, probably better way and) use a two-dimensional array.
   #for the sake of simplicity, we will use an array of hashes.
   #notice how the hashes do not have names, they are called anonymous hashes.
   #this means you can only access them through the array
 
for (0..$#users){ #iterate through the array
	#print the contents of the hashes inside
	print("Name:\t", $users[$_]{'Name'}, "\n", "Age:\t", $users[$_]{'Age'}, "\n\n");
}

For more info on multidimensional arrays, see Perldoc's page on complex data structures.

Subroutines

Subroutines in Perl provide an easy way to cut down on the length of your code and help increase code reuse.
In a way, they are like "functions", but don't work exactly like one; for example, you don't have to define a specific argument list or specify a return type; this is all defined by context.

sub1.pl

#!/usr/bin/perl
 
use strict;
 
for my $gay(qw|denvetta Pedrobear januszeal Deltantor|){
	#make a call to the sub 'isAGay' and print what it returns to us
	print isAGay($gay);
}
 
sub isAGay {
	#shift gets the first element in @_ (arguments sent to an array), and removes it from @_
	#it's useful for giving a sub's arguments more readable names instead of $_[0], $_[1], etc
	#you can also use the more verbose "shift @_" statement. but it does exactly the same;
	my $theGay = shift;
	#return specifies what the subroutine should return (obviously)
	#a subroutine can be used anywhere the type of data it returns can be
	#here we return a scalar, so we can use it in a print function just like normal
	return $theGay." is a gay.\n"; #use $_[0] in a sub just in case
}

Typeglobs

Modules

You can use modules in your programs like so.

use Module::Name;

CGI

Strict

use strict;
 
use strict "vars";
use strict "refs";

Using Strict makes catching errors easier, in many ways. Under strict, you are forced to declare all of your variables with the word my and failing to do so will result in an error. Strict also restricts you from using any symbolic references.
See also: perldoc strict

Warning

use warnings;
 
use warnings "all";

Using Warnings makes it so perl warns you of any mistakes or non-fatal problems with your perl code. It is recommended since it points out several common mistakes.
See also: perldoc warnings

Carp

Perl 6

Gay as fuck and slow as tits

Personal tools
Invasion Boards