Training

"Winners make choices,
losers make excuses.
"
Decide to be a Winner!!!!

±Arrows Getting Started

± Phase 1
Planning

± Website Tools

± Phase 3
Conceptual Design

± Helpful Information

± Phase 4
Physical Design

± Phase 5
Testing

± Phase 6
Implement and Market Website

± Other Web Development Items

± Multimedia

± Useful Utilities

± Programming

± Advanced Programming

± Microsoft Office Products

± Computer Maintenance

± Other


Web Design

NOTE: This is a collection of information and links collected over the years that might provide useful information. A Safer Company LLC does not guarantee, endorse or approve any of these links or their scripts. Use these links to other websites at your own risk.

Perl Cheat Sheet

  Unix

$ cat first.perl #displays contents of script

#!/usr/bin/perl #

Variables
 

Scalar

  • variable that holds single value string or number

$first_name="Jeanie";

$var="net";
print "${var}work"; #prints network

$now = localtime(); # prints local time Perl Function

  Scalar

Functions

defined Function - check for validity of a variable 1-defined; null if not defined

$name = "Tommy";
print "Okay \n" if defined $name;

undef Function - undefines a defined variable releases storage for arrays and subroutines

undef $name;

$_ - scalar variable - Holds the current line - $_ is the default output for the print function

$_="Jeanie";
print; #prints Jeanie

 

Array

  • an ordered list of scalars, indexed starting at 0

@names=("Jackson", "Penny", "Lily")

print "@names"; #prints the array

print "$names[0]"; #prints Jackson

print "$names[-1]"; #prints Lily

$names[3]="Smokie"; #assigns a new value as the 4th element

$size=@names; # the size of the array

$#arrayname - returns the last subscript (index) in the array.

@digits=(0..10); #numbers 0 - 10

@letters= ('A'..'Z, 'a'.. 'z''); # list of upper and lower case letters

@n=(-5..20); #numbers -5 - 20

  Array Slices

The resulting array when elements of one array are assigned the values from another array

@names=qw/jackson, lily, penny, jeanie, alex, lew/;
@pal=@names[2,3];
print "@pal";

  Multidimensional Arrays
  • called tables or matrices
  • consist of rows and columns
  • two dimensional array - first subscript represents the row and the second subscript represents the column
  • Each row enclosed in [ ] - unnamed list
  • there is an implied -> between adjacent brackets
  • -> arrow operator infix operator - can be used to get an individual element of an array. If the right side is either a [...] , {...} , or a (...) subscript, then the left side must be either a hard or symbolic reference to an array, a hash, or a subroutine respectively

# A two-dimensional array consisting of 4 rows and 3 columns
@matrix=( [ 3 , 4, 10 ], # Each row is an unnamed list
[ 2, 7, 12 ],
[ 0, 3, 4 ],
[ 6, 5, 9 ],
) ;
print "@matrix\n"; #prints the addresses of the four anonymous arrays
print "Row 0, column 0 is $matrix[0][0].\n"; #can also be written: $matrix[0]->[0]

print "Row 1, column 0 is $matrix[1][0].\n"; # can also be written: $matrix[1]->[0]
for($i=0; $i < 4; $i++){
for($x=0; $x < 3; $x++){
print "$matrix[$i][$x] ";
}
print "\n";
}

  Array Built-in Functions
  • pop removes last element
  • push adds new elements to the end of the array
  • shift removes first element
  • unshift adds new elements to the beginning of the array
  • sort sorts the elements of an array
     
87

Hash

  • an associative array
  • an unordered list of key/value pairs, indexed by strings
  • Key - the first string in the pair of strings - left side
  • Value - the second string - right side
  • Hash must be defined first
  • => digraph operator

%employee=(
"Name" => "Jeanie",
"City"=>"Winston Salem",
"State"=>"NC"
);
print "$employee{"Name"}"; #prints Jeanie$employee{"zip"}="27012"; #assigns a key / value

%seasons=("Sp" => "Spring",
"Su" => "Summer",
"F" => "Fall",
"W" => "Winter",
);
%days=("Mon" => "Monday",
"Tue" => "Tuesday",
"Wed" => undef,
);
$days{"Wed"}="Wednesday";
$days{5}="Friday";

90 Hash Slices a list of hash keys whose corresponding values are assigned to another list of keys.
91 Hashes of Hases  
118

keys Function

  • returns in random order the keys of the array

keys(ASSOC_ARRAY)

# The keys function returns the keys of a hash
%weekday= (
'1'=>'Monday',
'2'=>'Tuesday',
'3'=>'Wednesday',
'4'=>'Thursday',
'5'=>'Friday',
'6'=>'Saturday',
'7'=>'Sunday',
);
foreach $key ( keys(%weekday) ){print "$key ";}
print "\n";
foreach $key ( sort keys(%weekday) ) {
print "\t$key\t $weekday{$key}\n";
}
print "\n";

119

values Function

  • returns in random order an array of the values of a hash

 

# The values function returns the values in a hash
%weekday= (
'1'=>'Monday',
'2'=>'Tuesday',
'3'=>'Wednesday',
'4'=>'Thursday',
'5'=>'Friday',
'6'=>'Saturday',
'7'=>'Sunday',
);
foreach $value ( values(%weekday)){print "$value\n";}
print "\n";

foreach $value ( sort values(%weekday) ){print "$value\n ";}
print "\n";

122

Sort Hash by Values in Ascending Order

 

# Sorting a Hash by Value in Descending Order
sub asc_sort_wins {
$wins{$a} <=> $wins{$b};
}

# Sorting a Hash by Value in Descending Order
sub desc_sort_wins {
$wins{$b} <=> $wins{$a}; # Reverse $a and $b
}

 

%wins = (
"Portland Panthers" => 123410,
"Sunnyvale Sluggers" => 12,
"Chico Wildcats" => 5,
"Stevensville Tigers" => 6,
"Lewiston Blazers" => 11,
"Danville Terriors" => 8,
);

print "\nWins in Ascending Numeric Order by value:\n\n";
foreach $key (sort asc_sort_wins(keys(%wins))) {
printf "\t% -30s%5d\n", $key, $wins{$key};
}

print "\nWins in Descending Numeric Order by value:\n\n";
foreach $key (sort desc_sort_wins(keys(%wins))) {
printf "% -20s%5d\n", $key, $wins{$key};
}
print "\nSort Teams in Ascending Order by key:\n\n";
foreach $key( sort(keys(%wins))) {
printf "\t% -20s%5d\n", $key, $wins{$key};
}
print "\nSort Teams in Reverse Order by key:\n\n";
foreach $key( reverse sort(keys (%wins))) {
printf "\t% -20s%5d\n", $key, $wins{$key};
}

126

delete Function

  • deletes a value from a hash
  • deleted value return if successful

delete $ASSOC_ARRAY{KEY}

#!/usr/bin/perl
%employees=(
"Nightwatchman" => "Joe Blow",
"Janitor" => "Teddy Plunger",
"Clerk" => "Sally Olivetti",
);

$layoff=delete $employees{"Janitor"};
print "We had to let $layoff go.\n";
print "Our remaining staff includes: ";
print "\n";
while(($key, $value)=each(%employees)){
print "$key: $value\n";
}

127

exists Function

  • true if a hash key has been defined
  • false if not

exists $ASSOC_ARRAY(KEY)

%employees=( "Nightwatchman" => "Joe Blow",
"Janitor" => "Teddy Plunger",
"Clerk" => "Sally Olivetti",
);

print "The Nightwatchman exists.\n" if exists
$employees{"Nightwatchman"};
print "The Clerk exists.\n" if exists $employees{"Clerk"};
print "The Boss does not exist.\n" if not exists $employees{"Boss"};

     
 

Hash Built in Functions

  • keys retrieves all the keys in a hash
  • values retrieves all the values in a hash
  • each retrieves a key/value pair from a hash
  • delete removes a key/value pair
  Predefined Variables
$_ The default input and pattern-searching space.
$. Current line number for the last filehandle accessed.
$@ The Perl syntax error message from the last eval() operator.
$! Yields the current value of the error message, used with die.
$0 Contains the name of the program being executed.
$$ The process number of the Perl running this script.
$PERL_VERSION / $^V The revision, version, and subversion of the Perl interpreter.
@ARGV Contains the command-line arguments.
ARGV A special filehandle that iterates over command-line filenames in @ARGV.
@INC Search path for library files.
@_ Within a subroutine the array @_ contains the parameters passed to that subroutine.
%ENV The hash %ENV contains your current environment.
%SIG The hash %SIG contains signal handlers for signals.
 

Constant

  • once set, cannot be modified.

use constant BUFFER_SIZE => 4096;

use constant DEBUGGING => 0;

use constant ISBN => "0-13-028251-0";

ISBN="9-12-765438-0"; # Cannot modify ISBN; produces an error.

 

Numbers

  • decimal, octal, hexadecimal), floating point numbers, scientific notation, Booleans, and null.

$year = 2006; # integer

$mode = 0775; # octal number in base 8

$product_price = 29.95; # floating point number in base 10

$favorite_color = 0x33CC99; # integer in base 16 (hexadecimal)

$distance_to_moon=3.844e+5; # floating point in scientific notation

$bits = 0b10110110; # binary number

Quotation Marks
 

Single and Double Quotes

  • single Quotes - all characters are treated as literals
  • Double Quotes - Variables and special escape sequence ($ @ \) are understood.
  • make sure the quotes are matched
  • backslash sequences (\n, \t, \", etc.) are interpreted within double quotes
  • a backslash will escape a quotation mark, a single quote can be embedded in a set of double quotes, and a double quote can be embedded in a set of single quotes.

$question = 'He asked her if she wouldn\'t mind going to Spain'; # Single quotes

$answer = 'She said: "No, but it rains in Spain."'; # Single quotes

$line = "\tHe said he wouldn't take her to Spain\n";

$temperature = "78";

print "It is currently $temperature degrees";

# Prints: "It is currently 78 degrees.". Variables are

# interpreted when enclosed in double quotes, but not # single quotes

Escape Sequence Description
\t tab
\n new line
\r carriage return
\f Form Feed
\b backspace
\a alarm/bell
\e escape
\xff hexadecimal character
\c[ control character
\l next character converted to lowercase
\u next character converted to uppercase
\L next characters are converted to lowercase until \E is found
\U next characters are converted to uppercase until \E is found

 

Special Literals Description
_ _LINE_ _ current line number
_ _ FILE_ _ name of your script
_ _ END_ _

logical end of the file

Any trailing text will be ignored

<Ctrl>-d (-)\004 - Unix

<Ctrl>-z(\032) - MS DOS

_ _ DATA _ _

  • special literal

file handle to process textual data from within the script instead of external file

while(<DATA>){
#or while ($_=<DATA>) {
#or while ($inputline=<DATA>) {
print if /Norma/; # Print the lines if it finds/matches Norma
}
__DATA__
Steve Blenheim
Betty Boop
Igor Chevsky
Norma Cord
Jon DeLoach
Karen Evich

_ _ PACKAGE _ _ Represents the current package; default package is main
 

Here Document

  • is a block of text embedded between user-defined tags, the first tag preceded by <<.
  • NOTE: make sure there is not space after print

print<<END;
  It
  rains in
   Spain
END

 

Alternative Quotes

  • qq - double quote
  • q - single quote
  • qw - a quoted list of words ("January", "February", "March ")
  • qx - back quotes

print qq/Hello\n/; # same as: print "Hello\n";

print q/He owes $5.00/, \n"; # same as: print 'He owes $5.00', "\n";

@states=qw( ME MT CA FL ); # same as ("ME", "MT", "CA","FL")

$today = qx(date); # same as $today = 'date';

  • q/Hello/
  • q#Hello#
  • q(Hello)
  • q{Hello}
  • q[Hello]

Delimiter can be a non alphanumeric character such as #, !, or paired characters as ( ) , [ ], { }

  • q#Hello#
  • q(Hello)
 

printf();

  • Note: make sure there is not space after printf(
  • print function prints a formatted string to the selected filehandle, default being STDOUT
  • Return value
  • 1 - successful
  • 0 - fails
  • quoted string followed by comma and list of comma separated arguments

printf("<p>The name is %s and the number is %d</p>\n", "John", 50);

Conversion Definition
%b unsigned binary integer
%c

character

%d, i

%5d

decimal number
%e floating point number in scientific notation
%E floating point number in scientific notation using capital E
%f, %F floating point number
%g floating point number using either e or f conversion, whichever takes the least space
%G floating point number using either e or f conversion whichever takes the least space
%ld, %D Long decimal number
%lu, %U long unsigned decimal number
%lo, %O long octal number
%p pointer (hexadecimal)

%s

% -20s

string

printf("\tThe average of \n% 4s, \n% 4s, and \n% 4s is %.3f \n\n",
$num1, $num2, $num3, ($num1+$num2+$num3)/3);

%u unsigned decimal number
%x hexadecimal number
%X  
%lx  
%% print a literal percent sign
   
   
   

 

 

sprintf

  • just like printf function except it alls you to assign the formatted string to a variable
 
  Operators
Assignment =, +=, -=, *= , %=, ^=, &=, |=, .=
Numeric equality = =, !=, <=>
String equality eq, ne, cmp
Relational numeric >   >=  < <=
Relational string gt, ge, lt, le
Range 5 .. 10 # range between 5 and 10, increment by 1
Logical &&, and,  ||, or, XOR, xor,  !
Auto increment/decrement

++  --

  • placed before a variable - increment or decrement the variable by one before returning the value
  • placed after - increment or decrement after returning the value

$i = 0;
$j = 0;
print $i++; # prints 0
print ++$j; # prints 1

File -r, -w, -x,-o, -e, -z, -s, -f, -d, -l, etc.
Bitwise ~  &  |   ^   <<   >>
String concatenation .
String repetition

x

print '-' x 80; # print row of dashes

Arithmetic * / - + %
Pattern matching =~, !~
Conditionals
  if statement if ( $a == $b ){ print "$a is equal to $b"; }
  if/else statement

$coin_toss = int (rand(2 )) + 1; # Generate a random # number between 1 and 2

if( $coin_toss == 1 ) {

print "You tossed HEAD\n";

}

else {

print "You tossed TAIL\n";

}

  if/elsif statement

# 1 is Monday, 7 Sunday

$day_of_week = int(rand(7)) + 1;

print "Today is: $day_of_week\n";

if ( $day_of_week >=1 && $day_of_week <=4 ) {

print "Business hours are from 9 am to 9 pm\n";

} elsif ( $day_of_week == 5) {

print "Business hours are from 9 am to 6 pm\n";

} else {

print "We are closed on weekends\n";

}

  Conditional Operator

$coin_toss = int (rand(2 )) + 1; # Generate a random number

# between 1 and 2

print ( $coin_toss == 1 ? "You tossed HEAD\n" : "You tossed TAIL\n" );

Loops
 

while/until Loop

  • As long as the expression tests true, the loop continues to iterate

$count=0; # Initial value
while ($count < 10 ){

# Test print $n;

$count++; # Increment value

}

 

do-while

$count=0; # Initial value

do {

print "$n ";

$count++; # Increment value

while ($count < 10 ); # Test

}

  for Loop

  • first expression inititializes a variable and is evaluated only once.
  • second tests whether the value is true, and if it is true, the block is entered;
  • if not, the loop exits.

for( $count = 0; $count < 10; $count = $count + 1 ) {

print "$count\n";

}

  foreach Loop

@dessert = ( "ice cream", "cake", "pudding", "fruit");

foreach $choice (@dessert){

# Iterates through each element of the array

echo "Dessert choice is: $choice\n";

}

  Loop Control

$n=0;

while( $n < 10 ){

print $n;

if ($n == 3){

last; # Break out of loop

} $n++;

}

print "Out of the loop.<br>";

  Subroutines and Functions
 

Subroutines/Functions

  • block of code that performs a task and can be invoked from another part of the program. Data can be passed to the function via arguments. A function may or may not return a value.
  • Variables outside the function are available inside the function. The my function will make the specified variables local.

$my_year = 2000;
if ( is_leap_year( $my_year ) ) { # Call function with an argument
print "$my_year is a leap year\n";
}
else {
print "$my_year is not a leap year";
}

sub is_leap_year { # Function definition
my $year = shift(@_); # Shift off the year from
# the parameter list, @_
return ((($year % 4 == 0) && ($year % 100 != 0)) || ($year % 400 == 0)) ? 1 : 0; # What is returned from the function
}

  Files
 

Files

  • the open function to open files, and pipes for reading, writing, and appending. The open function takes a user-defined filehandle (normally a few uppercase characters) as its first argument and a string containing the symbol for read/write/append followed by the real path to the system file.

To open a file for reading:

open(FH, "<filename"); # Opens "filename" for reading.

# The < symbol is optional.

open (DB, "/home/ellie/myfile") or die "Can't open file: $!\n";

To open a file for writing:

open(FH, ">filename"); # Opens "filename" for writing.

# Creates or truncates file.

To open a file for appending:

open(FH, ">>filename"); # Opens "filename" for appending.

# Creates or appends to file.

To open a file for reading and writing:

open(FH, "+<filename"); # Opens "filename" for read, then write.

open(FH, "+>filename"); # Opens "filename" for write, then read.

To close a file:

close(FH);

To read from a file:

while(<FH>){ print; } # Read one line at a time from file.

@lines = <FH>; # Slurp all lines into an array.

print "@lines\n";

To write to a file:

open(FH, ">file") or die "Can't open file: $!\n";

print FH "This line is written to the file just opened.\n";

print FH "And this line is also written to the file just opened.\n";

To Test File Attributes

print "File is readable, writeable, and executable\n" if -r $file and -w _ and -x _;

# Is it readable, writeable, and executable?

print "File was last modified ",-M $file, " days ago.\n";

# When was it last modified?

print "File is a directory.\n " if -d $file; # Is it a directory?

94

Filehandles

  • STDIN -
  • STDOUT - output to the terminal screen
  • STDERR - printing errors
  • names given to predefined streams
  • stdin
  • stdout
  • stderr
  • <STDIN> next line of standard input can be read from the terminal
  • retains new line at the end of string Must chomp or chop
  • DATA - gets data from the same script

Ctrl-d UNIX

Ctrl-z Windows

95 Chop DON't USE removes the last character in the scalar variable and the last character of each word in an array

95

100

***Chomp
  • Perl 5
  • remove the last character in a scalar variable and the last character of each word in an array ONLY if that character is the new line
96 Read Function
  • reads a number of bytes into a variable from a specified filehandle.
  • Standard input is STDIN
  • Returns the number of bytes read.

number_of_bytes=read(FILEHANDLE, buffer, how_many_bytes);

97 getc function
  • gets a single character from the keyboard or from a file
  • at EOF, returns a null string

# Getting only one character of input
print "Answer y or n ";
$answer=getc; # Gets one character from stdin
$restofit=<>; # What remains in the input buffer is
# assigned to $restofit
print "$answer\n";
chomp($restofit);
if ($restofit ne "")
{print "The characters left in the input buffer were:*$restofit*\n" if defined $restofit;}

99 Assign input to a Hash

# Assign input to a hash
$course_number=101;
print "What is the name of course $course_number?";
chomp($course{$course_number} = <STDIN>);
print %course, "\n";

101 exists Function

returns true if array index or hash key has been defined and false if not.

#!/usr/bin/perl
@names = qw(Tom Raul Steve Jon);
print "Hello $names[1]\n", if exists $names[1];
print "Out of range!\n", if not exists $names[5];

101 delete Function

remove a value from a n element of an array but not the element itself. The deleted value is undefined.

@colors=("red","green","blue","yellow");
print "@colors\n";
delete $colors[1];
print "@colors\n";
print $colors[1],"\n";

102 grep Function

evaluates the expression (EXPR) for each element of the array *(LIST)

# Searching for patterns in a list
@list = (tomatoes, tomorrow, potatoes, phantom, Tommy);
$count = grep( /tom/i, @list); #counts the items 4 items found
@items= grep( /tom/i, @list); #assigns the items to a new array
print "Found items: @items\nNumber found: $count\n";

102 join Function

joins the elements of an array into a single sting and separates each with the given delimiter (the opposite of split)

join (DELIMITER, LIST)

# Joining each elements of a list with colons
$name="Joe Blow";
$birth="11/12/86";
$address="10 Main St.";
print join(":", $name, $birth, $address ), "\n";

103 map Function maps each of the values in an array to an expression or block returning another array with the results of the mapping.
107 pop Function

pops off the last element of an array and return it. The array size is decrease by 1.

$got=pop(@names);

108 push Function

pushes values onto the end of an array

push(ARRAY, LIST)

push(@names, "Jim", "Joseph", "Archie");

108 shift Function

shifts off and returns the first element of an array decreasing size by one

If ARRAY is omitted the ARGV array is shifted and if in a subroutine, the @_arry is shifted

109 splice Function

removes and replaces elements in an array.

splice (ARRAY, OFFSET, LENGTH, LIST)

OFFSET - the starting position
LENGTH - the number of items to be removed
LIST - new elements to replace the old ones

@discarded = splice(@colors, 2, 2);

110

split Function

  • splits up a string by some delimiter (white space by default) and returns an array.
  • DELIMITER -
  • EXPR - string to be split - defaults to $_
  • LIMIT - number of fields that can be split. Any remaining fields are part of the last one.

split("DELIMITER",EXPR, LIMIT)

$line="a b c d e";
@letter=split(' ',$line);

114

122

sort Function

  • sorts and returns a sorted array
  • if subroutine is omitted, sorts in string comparison order (alphabetically)
  • if subroutine is specid9ied the argument to sort is the name of the subroutine followed by a list of the values to be sorted.
  • cmp operator - values in the list will be sorted alphabetically (ASCII sort)
  • <=> operator (called the space ship) operator - the values sorted numerically and passed to the subroutine and received by special Perl variables $a and $b

sort (SUBROUTINE, LIST)

@list=("dog","cat", "bird","snake" );
print "Original list: @list\n";
# Ascii sort using a subroutine
sub asc_sort{
     $a cmp $b; # Sort ascending order
}

@sorted_list=sort asc_sort(@list);
print "Ascii sort: @sorted_list\n";

# Numeric sort using subroutine
sub numeric_sort {
     $a <=> $b ;
} # $a and $b are compared numerically

@number_sort=sort numeric_sort 10, 0, 5, 9.5, 10, 1000;
print "Numeric sort: @number_sort.\n";

116 Inline Function

# Sorting numbers with an unamed subroutine
@sorted_numbers= sort {$a <=> $b} (3,4,1,2);
print "The sorted numbers are: @sorted_numbers", ".\n";

116

reverse Function

  • reverses the elements in an array

@sorted = reverse (sort(@list));

117

unshift Function

  • prepends LIST to the front of the array.

unshift (ARRAY, LIST)

# Putting new elements at the front of a list
@names=("Jody", "Bert", "Tom") ;
unshift(@names, "Liz", "Daniel");
print "@names\n"; #Liz Daniel Jody Bert Tom

     
     
     
     
     
     
     
  Pipes
 

Pipes

  • Pipes can be used to send the output from system commands as input to Perl and to send Perl's output as input to a system command. To create a pipe, also called a filter, the open system call is used. It takes two arguments: a user-defined handle and the operating system command, either preceded or appended with the "|" symbol. If the command is preceded with a "|", the operating system command reads Perl output. If the command is appended with the "|" symbol, Perl reads from the pipe; if the command is prepended with "|", Perl writes to the pipe.

Input filter

open(F, " ls |") or die; # Open a pipe to read from

while(<F>){ print ; } # Prints list of UNIX files

Output filer

open(SORT, "| sort" ) or die; # Open pipe to write to

print SORT "dogs\ncats\nbirds\n"

# Sorts birds, cats, dogs on separate lines.

203

Regular Expressions - Pattern Matching

  • set of characters or pattern enclosed in forward slashes to match patterns in text and to refine searches and substitutions

print if

print if /Norma/; #prints line if Norma found

print $_ if $_ =~ /Norma/; # same as above line

print if else

print $x unless $x==6;

print unless /Norma/; #prints all lines with out Norma

print while

print $x++,"\n" while $x!= 5; #prints 1 - 4

print until

print $x++,"\n" until $x== 5; #prints 1 - 4

print foreach

@alpha=(a .. z, "\n");
print foreach @alpha;

Matching Patterns

m Modifier - matching patterns (m optional if using //)

/Regular Expression/ # same as m/Regular Expression/
m#Regular Expression#
m{Regular Expression} # can use { } ( ) [ ] <>

g Modifier - Global match

m /search pattern/g

$_ = "I lost my gloves in the clover, Love.";
@list=/love/g;
print "@list.\n"; #prints love love. Does not print Love because uppercase

i Modifier - run off case sensitivity

$_ = "I lost my gloves in the clover, Love.";
@list=/love/gi;
print "@list.\n"; #prints love love Love.

Special Scalars

$& - saves the search word

$_="San Francisco to Hong Kong\n";
/Francisco/; # Save 'Francisco' in $& if it is found
print $&,"\n";
/to/;
print $Ô,"\n"; # Save what comes before the string 'to'

/to\s/; # \s represents a space
print $Õ, "\n"; # Save what comes after the string 'to'

x Modifier - place comments within the regular expression and add whiter space characters (spaces, tabs, new lines) for clarity

$_="San Francisco to Hong Kong\n";
/Francisco # Searching for Francisco
/x;
print "Comments and spaces were removed and \$& is $&\n";

 

 

 

  Passing Arguments at the command Line  
  Reference Pointers  
 

Objects

Perl Class

a package containing a collection of variables and function called properties (attributes) and methods.

 
     
 

%ENV Hash

contains environment variables handed to Perl

 

#!/usr/bin/perl
foreach $key (keys(%ENV)){
print "\t$key\t$ENV{$key}\n";
}
print "\nYour login name $ENV{'LOGNAME'}\n";
$pwd=$ENV{'PWD'};
print "\n", $pwd, "\n";

 

%SIG Hash

set signal handlers for signals

 
 

%INC Hash

  • contains the entries for each filename that has been included via the do or require function
  • key - filename
  • value is the location
 
  Perl Documentation
 

perldoc -f reverse

  • type at command prompt
 
     
  Regular Expression Meta characters
 

Regular expression meta characters are characte4rs that do not represent themselves.

  • meta characters lose their special meaning if preceded with a backslash (\)

/^a . . . c/

  • caret(^) matches for a string only if it is at the beginning of the line.
  • period(.) used to match any single character including white space except a newline
  • [a-z0-9_] matches any single character in set

while(<DATA>){
print if /[A-Z][a-z]eve/; //prints if one capital letter, one lowercase letter and eve
}
__DATA__
Steve Blenheim 101
Betty Boop 201
Igor Chevsky 301
Norma Cord 401
Jonathan DeLoach 501
Karen Evich 601

while(<DATA>){ \\special DATA filehandle gets its input fro the text after the __DATA__ token. The while loop is entered and the first line following the __DATA__ token is read in and assigned to $_.
print "Found Norma!\n" if /N..ma/;
}
__DATA__
Steve Blenheim 101
Betty Boop 201
Igor Chevsky 301
Norma Cord 401
Jonathan DeLoach 501
Karen Evich 601

  • [^a-z0-9_] matches any single character not in set

while(<DATA>){
print if / [^123]0/; //prints if matches pattern one space, one number not in the range between 1 and 3, followed by 0
}

  • \d matches one digit represents the character class [0-9]
  • \D matches a nondigit, same as [^0-9]
  • \w matches an alphanumeric (word) character; same as [a-z0-9_]
  • \W matches a non alphanumeric (non word) character; same as [^a-z0-9_]
  • .\s matches a white space character, such as space, tabs, and newline's

# The s modifier and the newline
$_="Sing a song of sixpence\nA pocket full of rye.\n"; //scalar is assigned
print $& if /pence./s; //$& holds the pattern found in the last successful search id pence\n
print $& if /rye\../s; //\. means literal period (.) Searches for rye.\n
print if s/sixpence.A/twopence, a/s; \\smodifier allows the dot to match on the new line character

  • \S matches nonwhite space characters
  • \n matches a new line
  • \r matches a return
  • \t matches a tab
  • \f matches a form feed
  • \b matches a backspace
  • \0 matches a null character
  • \b matches a word boundary (when not inside [ ])
  • \B matches a non word boundary
  • ^ matches to beginning of line
  • $matches to end of line
  • \A matches to the beginning of the string only
  • \Z matches to the end of the string or line
  • \z matches to the end of the string only
  • \G matches when previous m//g left off

Greedy Metacharacters

  • x? matches 0 or 1 x
  • x* matches 0 or more occurrences of x
  • x+ matches 1 or more occurrences of x

 

  • (xyz)+ matches 1 or more patterns of xyz
  • x{m,n} matches at least m occurrences of x and no more than n occurrences of x
  • was|were\will matches one of was, were, or will
  • (string) used for back referencing
  • \1 or $1 matches first set of parentheses
  • \2 or $2 matches second set of parentheses
245

POSIX Character Class

  • Portable Operating System Interface used to ensure that programs are portable across operating systems.
  • different countries may vary the in way characters are encoded, the symbols used for currency, how times ns dates are represented.

Bracket Class Meaning

[:alnum:] alphanumeric characgters

[:alpha:] alphabetic characters

while(<DATA>){
print if /[[:upper:]][[:alpha:]]+ [[:upper:]][[:lower:]]+/; #Pattern=upper letter+one or more alphebetic lower case letters+ space + upper letter +one or more alphebetic lower case letters
}

   

while(<DATA>){
print if s/\s/*/g; # Substitute all spaces with stars
}

     
     
     
     
     
     

 

top of page

Page last updated: November 02, 2012 12:33 PM

It is all about:
Content and Navigation...

Web Site by: A Safer Company LLC