Back  Index  Next

Miscellaneous Topics

Perl is a very large subject. In this talk we cover several things that don't quite merit an entire class with labs, etc. This is more of a survey and overview of things that you might need someday. It is good to at least know that they are there. Give each of them a try and play around a little!

split and join


$line = "helen:34:f:123 main st:san francisco:90034";

@fields = split /:/, $line;

print "age: $fields[1]\n";        # 34
'split' takes a regular expression and a scalar and returns an array. It does a global search in the scalar for the regular expression and returns the array of the strings BETWEEN the places it matched. Another example:

$line = "hello,    blah, oops    ,     more,t";

@fields = split /\s*,\s*/, $line;

# @fields gets: hello blah oops more t
The opposite of split is 'join'.

@nums = (1, 4, 32, 2);

$numstr = join ":", @nums;   # 1:4:32:2
When an array is interpolated, Perl is using 'join' to put spaces between the elements of the array.

Input Record Separator

The special variable $/ is used to alter how lines are read from a file handle. It tells Perl what string (unfortunately not a pattern/regexp) to use to indicate the 'end of line'. Setting it to something other than the default "\n" allows you to read "paragraphs" or "chunks" at a time rather than lines at a time. Sometimes the unit of a line is not what you really want. For example, Setting it to "\n\n" will cause a program to read until it sees an entirely blank line. It will return a multi-line string with embedded newlines.

Setting $/ to 'undef' allows you to read an entire file in one fell swoop (because you will never encounter the undef value). Here is an example:


{
    local $/;
    open IN, "pic.jpg" or die;
    $picture = <IN>;
    close IN;
}
The use of 'local' above will cause $/ to be set to 'undef' for the <IN>. When the block is exited $/ will revert to its former value.

File Tests

Asking whether a file is readable or executable or whether it exists at all is very simple in Perl.

if (-r $fname) {
    print "$fname is readable\n";
}
if (-e $fname) {
    print "$fname DOES exist\n";
}
There are many letters to put after the dash. Check the documentation at "perldoc -f -X". Useful ones include:

r    readable
w    writable
x    executable
e    exists
T    text file
B    binary file
M    age of file

File and Directory Manipulation

Perl's heritage is from the Unix operating system. Nowhere is this more clear than in the names of the built in functions for manipulating files and directories.

chmod
chdir
rmdir
chown
unlink      (rm - delete a file)
rename      (mv)
With these functions you can manipulate files much like you would from the Unix command line. There are also these useful platform independent modules in the standard libary shipped with Perl:

File::Copy
File::Basename
File::Spec
File::Find
The latter enables easy recursive perusing of an entire directory structure.

Dates and Times in Perl


$t = time;        # get current time
This is the current time in seconds since January 1, 1970.

For details about day, month, year, etc use localtime.


($sec, $min, $hour, $mday, $mon,
 $year, $wday, $yday, $isdst    ) = localtime(time);
See "perldoc -f localtime" for details.

Random Numbers in Perl


$r = rand 10;
This gives a random real (fractional) number from 0 up to but not including 10. To generate a random dice roll of 1 to 6:

$roll = int(rand 6) + 1;
The function 'int' will chop off the fractional portion leaving only the integer from 0 to 5.

Or to choose a random element of an array:


$x = $nums[ rand @nums ];
@nums is in scalar context so will yield the size of the array. And "rand @nums" is in integer context so there will be an implied int( ). If you understand this, you have come a long ways to understanding the idea of context sensitivity in Perl!

splice

There are the functions shift, unshift, push and pop for dealing with the ends of arrays. 'splice' does everything you would ever want in the middle of the array. Full details at "perldoc -f splice".

Process Management

The 'system' function will execute an external program for you. On Unix you can give it any shell command (including redirection and pipelines).

system "who | grep me | wc -l >count";
Two other ways of doing this:

$count = `who | grep me | wc -l`;
Note the backquotes.

Or a line by line approach:


open IN, "who|" or die "cannot execute who\n";
while (<IN>) {
    next unless /me/;
    ++$count;
}
close IN;
This special parameter to 'open' effectively executes an arbitrary pipeline and reads from the standard output of it. You can also write to a pipeline. Nice!

The Environment

Environment variables are available to a Perl program by way of the %ENV hash:

# show all environment variables:
for $v (sort keys %ENV) {
    "$v\r$ENV{$v}\n";
}
If you put a new value into %ENV it will be seen by any subsequent program you run with 'system' or backquotes.

A Simple Database

Built into Perl is a very nice mechanism for keeping hashes on disk in a simple (but very useful) key-value database.

dbmopen %ages, "ages", 0644 or die "can't make ages dbm file";

$data{Jon} = 53;
$data{Pam} = 34;
$data{Harry} = 2;
It looks like this data is going into a normal hash in memory but in actuality it is going to a file on your hard disk!

You can quit the program and later do this:


dbmopen %ages, "ages", 0644 or die "cannot open ages\n";

print $ages{Harry};        # prints 2!

Back  Index  Next