perl notes

perl 183 chap 6

some of this content may have been taken from the book beginning perl from the amazon store. i own this book and these are my notes from it.
scalar – one number or string
vector – multiple numbers
constant – doesnt change
literal – number or string which means nothing but the number or string itself
interpolated – introducing or inserting something
quantifiers – The metacharacters that we use to deal with a number of characters in a row
start interactive perl shell:
perl -d -e 1
True and false.

TRUE = anything not 0
Using use strict; tells Perl you want to be prevented from implicitly creating global variables, which is why you should always use use strict; (and use warnings;) in your programs.

goes at the top of the perl script:
#!/usr/bin/perl -w

to print text:

print “Hello n”;

print 25_000_000, ” “, -4, “n”;   #prints 25,00,000 then a space, then -4, then a new line

false = ‘0’ / “” /  ()
print “This is”;
print “a block”;
print “of statements.n”;

you can put blocks inside of blocks

t Tab
n Start a new line (Usually called ‘newline’)
b Back up one character (‘backspace’)
a Alarm (Rings the system bell)
x{1F18} Unicode character

perl recognizes octal number if you put a zero in front of the number
for example:

print 01101;      #prints the number 577

perl recognizes hexadecimal if you put “0x” in front of the number:
print 0xBEEF;    #prints 48879

perl recognizes hexadecimal if you put “0b” in front of the number
print 0b11111111 #prints 255

printing out the literal values of numbers in different numbering systems:
print (“0xFFG”);     #prints 0xFFG
print “0x95”;        #prints 0x95
print oct(“30”)      #prints 24
print oct(“030”)     #prints 24
order of operations: ** * / % + –

print “95” + “5”;   #prints 100

print “21 from 25 is: “, 25 – 21, “n”;  #prints 21 from 25 is: 4
print “4 + 13 – 7 is:”, 4+13-7, “n”;    #prints 4 + 13 – 7 is : 10

to cause perl to do math in a different order use the parenthesis around what you want to process first
print(3 + 7) * 15;

to cause perl to multiply by the power of a number use **

print 5**5;    #prints 3125
print 5**2     #prints 25

if you are trying to use a negative number use the parathesis to do it correct
print (-5)**2;   #prints 25

i tried this and this did not work properly. I do not yet know how to do math to the power of a number
if the number is negative

operators: AND = “&” / OR = “|” / XOR = “^” / NOT = “~”

Comparing numbers:
compare if they are equal with the “==” operator
print 6==6;  #prints 1
print 6==1;  #prints nothing (the answer is false)

print”Five is more than six? “, 5 > 6, “n”;          #prints nothing
print “Seven is less than sixteen? “, 7 < 16, “n”;   #prints 1
print “Two is equal to two? “, 2 == 2, “n”;          #prints 1
print “One is more than one? “, 1 > 1, “n”;          #prints nothing
print “Six is not equal to seven? “, 6 != 7, “n”;    #prints 1


&& = and
|| = or
!  = not

when working with boolean operators be aware of presendence as some operators have higher presedence that the boolean operators
for example

print !2>3  #prints nothing
print !(2>3) #prints 1
Can be quoted with “” or ”
when quoting with ” no extra prosessing is done in the string execpt if you have or ‘
when you write a strin like:
print “$me says hello n”;
and there is a variable like $me = “casey”;
it will print “Casey says hello”

when using “” for a string use to print out a character. this happens because is the escape character so
you use 2 of them to print out the literal value of

there is also a feature where you can “quote text” with a non-quote character.
by starting text with a qCHARACTER then ending the text with CHARACTER for one quote or qqCHARACHTER you can quote the text
CHARACTER can be any non-aplhanumeric character.
Like this:
print qq|'”Hi,” said Jack. “Have you read /. today?”‘n|;
print qq#'”Hi,” said Jack. “Have you read /. today?”‘n#;
print qq(‘”Hi,” said Jack. “Have you read /. today?”‘n);
print qq<‘”Hi,” said Jack. “Have you read /. today?”‘n>;

if you have a bunch of words that make up a list (‘test’ , ‘test2’ , ‘test3’) you can quote the list like follows:

for example qw( test test2 test3 );

the “here-document”:

the final way to quote a staring is as follows.
You create an identifier and it is used at the start, and end of the block of text.
then that “quotes” the text in the block.
A here-document must start with << and then a label. The label can be anything you choose, but is
traditionall EOF (End Of File). The label must follow directly after the arrows with no spaces between,
unless the same number of spaces precedes the end marker. It ends when the label is found at the
beginning of a line.


use warnings;
This is a here-document. It starts on the line after the two arrows,
and it ends when the text following the arrows is found at the beginning
of a line, like this:

print “HELLO” x3;  #prints hello 3 times in a row
print “HELLO” x(3-1); #prints hello 2 times in a row

the “.” joins strings

print “hello” . ” my” . ” name” . ” is” . ” casey”  #prints hello my name is casey

comapring strings:
string comparison is based off the ascii characters number.

so A (which equals 97) is less that a (which eauals 97)

you can print out the number that represents the character by using the ord function:
print ord(“A”); #prints 97

there are string comparison operators and they as follows:
less than = “lt”
greater than = “gt”
equal to = “eq”
not equal = “ne”
compare = “cmp”

the cmp functions works as follows.
it takes 2 values, one on the left side, one on the right side.
if the value on the left side is less than the value on the right side it gives: -1
if the value on the left side is equal to the value on the right side it gives: 0
if the value on the right hand side is greater than the left hand side it gives: 1

the other operators:
print 1 lt 2;  #prints 1 because one is less than 2


when you use “my” infront a variable it keeps it scope local to the code block.
if you do not use the “my” keyword the scope is global for the current file.

in perl there are 3 types of data: scalars, lists, and hashes.
you store these in the following variables: scalar variable, arrays, and hashes

the scalar variable: a string of characters with a $ preceeding it.

$cat= “sterling”;   #cats value is set to “sterling”

to use the variable do the following:
print “my cats name is “, $cat, “n”;  #prints out “my cats name is sterling”

you can also store the result of an operation in a variable like so:
$a = 2+2;  #now $a = 4

then late you could do:
$a = $a + 4;   #$a now equals 8

$scalar = “1 2 3 4 5 6”;
print $scalar; #prints 1 2 3 4 5 6

— and ++ repsectively.
When they precede a variable, they act before everything else. If they
come afterwards, they act after everything else.


$a = 4;
$b = 10;

$b = $a++   #b is set to equal a, then a is incremented

$b = ++$a*2 #a is incremented, them multiplied by 2, then the value is assigned to $b

The autoincrement operator actually does something interesting if the variable contains a string of only
alphabetic characters, followed optionally by numeric characters. Instead of converting to a number,
perl ‘advances’ the variable along the ranges a-z, A-Z, and 0-9. This is more easily understood from a
few examples:
use warnings;
$a = “A9”; print ++$a, “n”;
$a = “bz”; print ++$a, “n”;
$a = “Zz”; print ++$a, “n”;
$a = “z9”; print ++$a, “n”;
$a = “9z”; print ++$a, “n”;
Should produce:
perl auto2.plx
This shows that a 9 turns into a 0 and increments the next digit left. A ‘z’ turns into an ‘a’ and
increments the next digit left. If there are no more digits to the left, either an ‘a’ or an ‘A’ is created,
depending on the case of the current leftmost digit.

variables inside strings:
inside a double quoted staring the variable name gets converted to its value.
this is not true with a single quoted string.
$name = “Casey”;

print ‘My name is $namen’;  #My name is $name
print “My name is $namen”;  #My name is Casey

you can get user input by using <STDIN>

print “please enter a value”;
$value = <STDIN>;
an empty list looks like this: “()” (without the quotes)

A list of words: (“test” , “test2” , “test3”);

to create a list and print the 3rd value of it (counting starts from zero)

print ((‘zero’, ‘one’, ‘two’) [2]);  #prints two

print ((‘zero’, ‘one’, ‘two’) [-1]); #prints two

we can also print multiple values:

print ((19, 68, 47, 60, 53, 51, 58, 55, 47)[4, 5, 6]);  #prints 535158
print ((19, 68, 47, 60, 53, 51, 58, 55, 47)[(4, 5, 6)]);  #prints 535158

rages in lists. using the “..” we can fill in the missing values:
print (1 .. 6);   #prints 123456
print(a .. z);    #prints abcdefghijklmnopqrstuvwxyz

to have it print backwards:
print reverse(6 .. 1);  #prints 654321
print reverse(a .. z);  #prints zyxwvutsrqponmlkjihgfedcba

print with text inbetween ( a selection of text and values in one print statement:
print “The other half (backwards): “, reverse(‘n’ .. ‘z’), “n”;

you tell perl you want to create an array using the “@” character.

for example:

my @myarray;
@myarray = qw( test test1 test2 );

counting the letements in an array:
@array1 = qw(Monday Tuesday Wednesday Thursday Friday Saturday Sunday);
$scalar1 = @array1

print $scalar1; #prints 7

my @array;
@array = (4, 6, 3, 9, 12, 10);
print @array; #prints 46391210
print “@array”;  #prints 4 6 3 9 12 10

so when you put “” around the name of an array, it prints it with spaces between the elements.

filling one array with the values of another:
@array1 = @array2;  #fills @array2 with the values of array1. now this assumes both have been previously declared.

accessing an element in an array:
$array[2] = 12 #array 3 now equls 12

adding to the array:
my @array1 = (1, 2, 3);
my @array2;
@array2 = (@array1, 4, 5, 6);

do iteratre through the parts of an array you can create variable and then assign the array to them
when you do this the first variable equals the value from bucket [0] from the array.
the second veriable equals [1] from the array , and so on.
@hello = (1,2,3);
($one,$two,$three) = @hello;
print $one  #prints one

you can also use the subscript syntax like follows:
print @hello[1]   #prints 2

accessing mutiple parts of the array:
print @hello[0,2]; #prints 13

an array also works like a stack. you can use the push and pop instructions to add or remove data from
the stack.
@hello = (1,2,3);
pop @hello;
print @hello;  #prints 12

you can pop values off the stack, and into avariable like below:
my @names = (‘Foo’, ‘Bar’, ‘Baz’);
my $last_one = pop @names;

then there is the push instruction:
@names = (‘hello1’, ‘hello2’);
push @names, ‘hello3’;
print @names;    #prints hello1hello2hello3
print “@names”;  #prints hello1 hello2 hello3

you can also push an array onto another the end of another array:
my @others = (‘Darth’, ‘Vader’);
push @names, @others;
print “@namesn”; # Foo Bar Moo Darth Vader



my @names = (‘Foo’, ‘Bar’, ‘Moo’);
my $first = shift @names;
print “$firstn”; # Foo
print “@namesn”; # Bar Moo
here shift knocks out the left most value into the variable $first.
the array is them left with all the values besides that value

my @names = (‘Foo’, ‘Bar’);
unshift @names, ‘Moo’;
print “@namesn”; # Moo Foo Bar


my @unsorted = (1, 2, 11, 24, 3, 36, 40, 4);
my @string = sort { $a cmp $b } @unsorted;   #does a comparison on values a and b (created by the sort function auto)
print “String sort: @stringn”;              #the comparison is on array @unsorted
my @number = sort { $a <=> $b } @unsorted;
print “Numeric sort: @numbern”;

Stringsort: 111224336440
Numericsort: 123411243640
Denoted by the % symbol (%myhash)
Hash keys must be unique. You cannot have more than one entry for the same name,
and if you try to add a new entry with the same key as an existing entry,the old one
will be over-written. Hash values meanwhile need not be unique

2 ways of writing the hash out:

Gary => “Dallas”,
Lucy => “Exeter”,
Ian => “Reading”,
Samantha => “Oregon”

or this way:
“Gary” , “Dallas”,
“Lucy” , “Exeter”,
“Ian” , “Reading”,
“Samantha” , “Oregon”

the difference is the comma or seperator in the hash definition

You can convert arrays to hashes, and back to hashes like below:
@array = qw(Gary Dallas Lucy Exeter Ian Reading Samantha Oregon);
print @array
%where = “@array”; #notice the parenthesis, it causes the names to be imported in the same order, with spaces, without problems
print %where; #prints Gary Dallas Lucy Exeter Ian Reading Samantha Oregon

How to create and address hashes:
%ahash = (‘test’, ‘yes’);   #creation of hash with one key and value pair
print $ahash{test};         #print out value of ahash key “test”

setting the value of a key:
$ahash{akey} = “avalue”;

gets rid of new line characters (/n) at the end of a line.
if there is a second line it does not get rid of the new line character.
$myvariable = <STDIN>;
notice that in the IF loops that when you write “if (x == x)” there is no “;”
$_  = special varbiable that is used when looping. example: when you do a foreach $myname (@array)  $myname is the current
variable being iterated over. so $myname is == to $_
The keyword last, in the body of a loop, will make perl immediately exit, or ‘break out of’ that loop.
If you want to skip the rest of the processing of the body, but don’t want to exit the loop, you can use next
to immediately go back to the start of the loop, passing the next value to the iterator.

@arrayme = (1,2,3,4)
foreach $temp (@arrayme){ print “HELLO n”;} #pritns hello 4 times
foreach (@arrayme){ print “$_ n”;}


if ($password eq $guess) { print “Pass, friend.n”; }
else { die “Go away, imposter!n”; }

another example:
if ( <condition 1> ) {
} else {
if ( <condition 2> ) {
<second action>
} else {
if ( <condition 3> ) {
<third action>
} else {
<if all else fails>

using elseif:

if ($weather eq “snowing”) {
print “OK, let’s go!n”;
} elsif ($weather eq “raining”) {
print “No way, sorry, I’m staying in.n”;}

checking if something is not zero before continuing:

exists $rates
or die “I don’t know anything about {$to} as a currencyn”;


my $countdown = 5;
while ($countdown > 0) {
print “Counting down: $countdownn”;

do { print “test n”; } while ($x == 1);

my @array = ( “red”, “blue”, “STOP THIS NOW”, “green”);

for (@array) {
last if $_ eq “STOP THIS NOW”;
print “Today’s colour is $_ n”; }


you can use the keyword “next” anytime during the loop to end the current processing of the current irterator
and go on to the next one (going to the loop beginning with the next iterator)

to create a regular expression you put the text in between /texthere/
“texthere” is the text to match

note when using regex you must use ~ with your evaluations. if you do not it matches almost anything.
for example
!~  = not equal to
~=  = equal to

$myvar = “fish”;
if ($myvar !~ /fish/) { print “hello n”; }  #if not equal to then print
if ($myvar != /fish/) { print “hello n”; }  #if not equal to then print
if ($myvar == /fish/) { print “hello n”; }  #if equal then print

Characters that have special meanings. you will need to use a then the character if you want to use literally. example:(*)
. * ? + [ ] ( ) { } ^ $ |

to check if a character is at the end of a string use $
to check if a character is at the beginning of a string use ^

for example to search if there is a period at the end of the text use: “.$”
to search if a L is at the beginning of the text use: “^L”

searching for multiple characters in a position using []
t[hml]e  #searches for the, tme, and tle

searching for text which does not contain characters:
th[^eo]   #searches for string which DO NOT have e or o after “th”

check the regex special characters fi;

search for just alpha characters:
/{a-z]/i  #the i makes it case insensitive

match one or the other

there is also the b option which will match anything that can be used to separate words.
the s matches spaces, but the b option will match punctuation which separates words


to match text where a letter might be present:
for the words he and she: /bs?heb/

/bea?t/   Matches either ‘beat’ or ‘bet’
/bea+t/   Matches ‘beat’, ‘beaat’, ‘beaaat’…
/bea*t/   Matches ‘bet’, ‘beat’, ‘beaat’
to work with a file you create what is called a file handle.
three system file handlers are always available: <STDOUT> <STDIN> <STDERR>
you can create a file handle as shown below:

open MYFILEHANDLENAME, ‘filename.txt’ or die $!;

the first part is the command (open) the second part is the internal name for this file handle (MYFILEHANDLENAME)
after that we see that it takes a file name as an argument. the “or die $!” is to simply stop and throw an error. the $! gives error info.

read/write     +<
read/write     +>  overwrites existing file / creates file
read/append     +>> creates file / does not overwrite file

open MYFILEHANDLENAME, ‘c:/filename.txt’ or die “our error was: $!”;
open MYFILEHANDLENAME, ‘c:filename.txt’ or die “our error was: $!”;
open READ, ‘C:UsersFuiontest.txt’ or die $!;

reading the contents of a file:
while (<FILEHANDLENAME>) { print $_ ;}

writing to a file:
when you open file handles you can only read or write, you can not do both
open WRITE, “> myfile.txt” or die $!;     #write to a file overwriting whatever is in it
open WRITE, “>> myfile.txt” or die $!;    #append to a file

open WRITE, ‘>> C:UsersFuiontext.txt’ or die $!;

An example session of reading and writing to a file:
open RW , “+>>testfile.txt” or die $!;
print RW “test123”;
close RW;
open READ, “testfile.txt” or die $!;
while (<READ>) {print $_;}
close READ;



to change the defualt filehandle ( default is <STDOUT> ) remember to set STDOUT back when your done



Leave a Reply