Professional Documents
Culture Documents
Perl P3
Perl P3
Ramiz Ahmed
Hashes
● Associate keys with values.
● Allows for almost instantaneous lookup of a value that
is associated with some particular key.
numbers, … “ID” 32
“time” 21.4
“name” “Fred”
$areaOfFirstCircle = areaOfCircle(5);
print("$areaOfFirstCircle\n");
sub areaOfCircle {
$radius = $_[0];
return(3.1415 * ($radius ** 2));
}
firstSub(1, 2, 3, 4, 5, 6);
firstSub(1..3);
firstSub("A".."Z");
sub firstSub {
$numParameters = @_ ;
print("The number of parameters is
$numParameters\n");
}
Passing Parameters to Functions
To write a file
#!/usr/bin/perl
#!perl
# ------------------------------------
# FILE OUTPUT
# ------------------------------------
# this will open an existing file “test.txt” to append
open MY_FILE, “>>test.txt”;
#!perl
# ------------------------------------
# FILE INPUT
# ------------------------------------
# this will open a file “test.txt” to read
open MY_FILE, “<test.txt”;
while( defined( my $line= <MY_FILE> ) ) {
print $line; # print one line read from a file
}
opendir(DIR,“/mnt/home") or
die "NO SUCH Directory: Images";
while ($file = readdir(DIR) ) {
print " $file\n";
}
closedir(DIR);
Reading and Writing Files
$sentence =~ /the/
True if $sentence contains "the"
$sentence = "The dog bites.";
if ($sentence =~ /the/) # is false
…because Perl is case-sensitive
!~ is "does not contain"
Square brackets
[qjk] # Either q or j or k