Quick Overview
scalar names begin with $
array names begin with @
hash names begin with %
my indicates private (local) variable
if not declared with my, then variable is
global (package)
@weekend = (“Saturday“, “Sunday”);
print “@weekend”;
print “I love “.$weekend[0].”\n”;
http://www.cs.mcgill.ca/~abatko/computers/programming/perl/howto/hash /
my %hash = (); #clear hash
# add entries using literals & variables
$hash{ 'CSCI306' } = 'Java';
$l = 'C++';
$c = 'CSCI261';
$hash{$c} = $l;
# print size and all entries
print "size of hash: " . keys( %hash ) . ".\n";
for my $key ( keys %hash ) {
my $value = $hash{$key};
print "$key => $value\n";
}
# search for entry
if ($hash{$c} ne "") {
print $hash{$c}."\n";
}
$filename = "data.txt";
# open file, DATA is file handle
open(DATA,$filename);
# read file into array
@data = ;
# process each line read from file
foreach $line (@data)
{
# split places elements into array, based on
# delimiter. Many other options, do a Google
@words = split(/ /,$line);
foreach $word (@words)
{
print($word."\n");
}
}
# good to declare subs at top of program, not
required
sub trim;
…
$trimmedString = &trim($myString);
..
sub trim($)
{
# can get parameters using shift
my $string = shift;
# regex to remove whitespace \s
#^ is beginning, $ is end
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
match text
$string =~ /target/;
match beginning
$string =~ /^target/;
match end
$string =~ /target$/;
match ignore case
$string =~ /target/i;
remove punctuation
$string =~ s/\W/ /g;
simple replacement
$string =~ /target/replacement/;