Perl


What is Perl?


Scalars


Number Literals

 123 123.45 .45 123. 1e2 .45e2 1.23e-2

String Literals

 'The yellow fox\n jumped over the fence'
 "CD \t Artist \t Title \t Play Time"

More About String Literals

 q$I don't want to stay$
 qq#"I am late!", said the rabbit#

Scalar Variables

 $firstname
 $firstName
 $FirstName
 "The answer to Life, the Universe and Everything is $answer"

Predefined Variables


perldoc

 perldoc perlvar

Arithmetic Operators

 5/2 => 2.5

String Operators

 "front" . " " . "page"
 "front page"
 "More! " x 3
 "More! More! More! "

Predefined Functions on Strings

 doit x

 doit(x)

 chomp "hello, world!\n"
 "hello, world!"
 join '_', 'a', 'yellow', 'fox'
 'a_yellow_fox'

Assignments

 $salary = 40000;
 $salary += $raise;

Input from the Console

 $data = <STDIN>;
 $data = <STDIN>;
 chomp $data;
 chomp($data = <STDIN>);

Output to the Console

 print "One, ", $two, "buckle my shoe\n";
 #!/usr/bin/perl -w

print "Name: "; $name = <STDIN>; chomp $name;

print "Surname: "; $surname = <STDIN>; chomp $surname;

print "Welcome, $name $surname!\n";


"Here" Documents

 print << HERE;
 print << HERE;
 <tr>
	<th>$name</th>
	<td>$ENV{$name}</td>
 </tr>
 HERE

Control Structures


Note On Conditions

 $number
 while ($next = <STDIN>) { ... }

Relational Expressions

 ==	!=	<	>	<=	>=
 eq	ne	lt	gt	le	ge

Complex Conditions

 and	&&
 or	||
 not	!
 (($name eq "Lucy") && ($age >= 18))

Conditional Branches

 if ($salary > 50000) {
	$taxRate = .50;
 } elsif ($salary > 30000) {
	$taxRate = .40;
 } else {
	$taxRate = .30;
 }

 unless ($link) {
	print "No link provided";
 }


Loops

 $n = 0;
 while ($next = <STDIN>) {
	chomp $next;
	if ($next eq "Rheostatics") {
		$n++;
	}
 }
 print "Rheostatics occurs $n times\n";

Special Variable $_

 $n = 0;
 while (<STDIN>) {
	chomp;
	if ($next eq "Rheostatics") {
		$n++;
	}
 }
 print "Rheostatics occurs $n times\n";