Perl Notes
Below are the commands for
- Perl program setup
- Variables
- Arrays
- DBM
- String search and manipulation
- Other
----------------------------------------------------
PERL PROGRAM SETUP
Perl progams read in arguments in a similar way to C
$numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";
foreach $argnum (0 .. $#ARGV) {
print "$ARGV[$argnum]\n";
}
----------------------------------------------------
VARIABLES
my $myvar;
my @mylist;
my %myhash = ();
$myhash{$key} = $value;
for $key (keys %myhash) {;}
print "size of hash: " . keys( %hash ) . ".\n";
print "Value EXISTS, but may be undefined.\n" if exists $hash{ $key };
my %hash_copy = %hash; # copy a hash
----------------------------------------------------
ARRAYS
----------------------------------------------------
DBM
----------------------------------------------------
STRING SEARCH AND MANIPULATION
crypt(STRING1, STRING2) -- Encrypts STRING1
index(STRING, SUBSTRING, POSITION) -- Returns the position
of the first occurrence of SUBSTRING in STRING at or
after POSITION.
lc(STRING) -- Returns a string with every letter of STRING
in lowercase. For instance, lc("ABCD") returns "abcd".
length(STRING) -- Returns the length of STRING.
split(PATTERN, STRING, LIMIT) -- Breaks up a string based
on some delimiter. In an array context, it returns a
list of the things that were found. In a scalar
context, it returns the number of things found.
if ($string =~ m/regex/) {
print 'match';
} else {
print 'no match';
}
Perl has a host of special variables that get filled after
every m// or s/// regex match. $1, $2, $3, etc. hold the
backreferences. $+ holds the last (highest-numbered)
backreference. $& (dollar ampersand) holds the entire regex
match.
@- is an array of match-start indices into the string. $-[0]
holds the start of the entire regex match, $-[1] the start
of the first backreference, etc. Likewise, @+ holds
match-end indices (ends, not lengths).
$' (dollar followed by an apostrophe or single quote) holds
the part of the string after (to the right of) the regex
match. $` (dollar backtick) holds the part of the string
before (to the left of) the regex match. Using these
variables is not recommended in scripts when performance
matters, as it causes Perl to slow down all regex matches in
your entire script.
All these variables are read-only, and persist until the
next regex match is attempted.
----------------------------------------------------
HASH and MYSQL
my $answers = 'a,b,c,d,e';
my $sql = "select max_time, $answers from questions " .
'where question_number=?';
my $hash_ref = sql_fetch_hashref( $sql, $q );
my @answers = split ',', $answers;
my $max_time = $hash_ref->{max_time} || '60';
my $hash_ref_ans;
for my $letter ( @answers ) {
$hash_ref_ans->{ $letter } = $hash_ref->{ $letter }
if defined $hash_ref->{ $letter };
}
|